user1876942
user1876942

Reputation: 1501

Save a Matlab Property to a mat file

I have a class with a struct property called myStruct:

properties
   myStruct;
end

I would like to save the struct to a .mat file. I tried:

save -append registers.mat myStruct;

But it gives the error:

Variable 'myStruct' not found.

I have different functions for updating the struct, like:

    function configureChannel( obj, Channel )
       myStruct.Channel = Channel;
       save -append registers.mat myStruct;
    end  

    function updateConfiguration( obj, dataPath )
       myStruct.EN = 1;
       save -append registers.mat myStruct;
    end  

These are all functions of the same class.

Upvotes: 1

Views: 639

Answers (1)

Dev-iL
Dev-iL

Reputation: 24169

I think that the main problem in this code is how you access myStruct from your functions. Take a look at the following piece of code:

function configureChannel( obj, Channel )
  myStruct.Channel = Channel;
  ...
end

What you intended for it to do was to assign Channel into the Channel field of the current object's myStruct's Channel property. What it actually does is equivalent to calling:

myStruct = struct('Channel', Channel);

That is, you create a new local variable in the current workspace/scope of configureChannel, without actually updating the property of the object, obj.

So the first correction you need to make is how you access myStruct in your setter:

obj.myStruct.Channel = Channel;

Next is the issue of saving.

When dumping a copy of an object's field to a file, I would expect save to treat your arbitrary object as a struct, and so struct saving conventions should apply:

'-struct',structName | Store the fields of the scalar structure specified by structName as individual variables in the file. For example, save('filename.mat','-struct','S') saves the scalar structure, S.

Thus, I would expect the following to work disclaimer: I didn't test it:

save('filename.mat','-struct','obj.myStruct');

Other alternatives in case the above fails:

save('filename.mat','obj.myStruct');            % Alternative #1
tmp = obj.myStruct; save('filename.mat','tmp'); % Alternative #2

One last thing - as you may have noticed, I'm using the function form of save, because I consider it to be more maintainable/readable/fool-proof:

save(filename,variables,'-append');

Upvotes: 2

Related Questions