Convert from struc to a .mat file
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
Walter Roberson
2011-8-30
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 个评论
Walter Roberson
2011-8-30
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...
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Workspace Variables and MAT Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!