Convert from struc to a .mat file

1 view (last 30 days)
Diana Acreala
Diana Acreala on 30 Aug 2011
Hello all!
Please help me!I have a problem and I found no solution!!
I have my file.mat. I used 'WS=whos('-file', FileName)' to save my file as a structure. Now i need to add new variables in my structure and after that to convert my new structure back in a .mat file.
I tried to use: 'save ('file.mat', '-struct', 'WS')' but it gives me this error: '??? Error using ==> save The argument to -STRUCT must be the name of a scalar structure variable.'
Waiting for your help... Thanks

Answers (1)

Walter Roberson
Walter Roberson on 30 Aug 2011
WS = whos('-file', FileName)
does not save the file as a structure: it only gets you the names and other information about the variables that are stored in the files, without getting their values.
The information returned by whos() is a structure array, one element per variable in the file. This conflicts with the requirement of save -struct that "the argument to -STRUCT must be the name of a scalar structure variable" (emphasis added). WS is not a scalar structure variable.
If you are wanting to load your file as a structure then you should use
WS = load(FileName);
This will be a scalar structure array, with one field for each variable name in the file. You can use fieldnames(WS) to find the names of the variables.
  3 Comments
Walter Roberson
Walter Roberson on 30 Aug 2011
As I indicated, the whos() does not load the _content_ of any of the variables. Are you certain that you want to create the .mat file without ever having looked at the actual content of the old one?
But if you really need it, here is code that will convert the non-scalar structure array WS to the scalar structure array WS2 with each WS(K) becoming a field in WS2 named according to WS(K).name
for K = 1 : length(WS)
WS2.(WS(K).name) = WS(K);
end
save('file.mat', '-struct', 'WS2')
Practical uses for this do not seem immediately obvious to me...
Diana Acreala
Diana Acreala on 30 Aug 2011
GREAT! Now it's working:) Thank you!
Have a nice day!:D

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!