Sometimes you need to save the variables from your base workspace, but using "save" function will have them all stored individually so if you reload them into a new workspace it could be a mess, and some variables could be overwritten.
With this function, you can save all of them into a struct array, and so they'll be nicely packaged and ready to be saved to a .mat file that, when reloaded, will be easy to identify.
Example:
a='LALALA'
b=[1:12:258]
c={'cell1', 'cell2', 'cell3'}
d=768
e=true(3)
theworkspace=ws2struct();
theworkspace =
a: 'LALALA'
b: [1x22 double]
c: {'cell1' 'cell2' 'cell3'}
d: 768
e: [3x3 logical]
Andres (2021). Save Workspace to Struct (https://www.mathworks.com/matlabcentral/fileexchange/36257-save-workspace-to-struct), MATLAB Central File Exchange. Retrieved .
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Create scripts with code, output, and formatted text in a single executable document.
Cobeldick, you da real MVP.
@Adrien Peyrache: because using EVAL is pointless and slow, just like ASSIGNIN is:
https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
In any case this submission does nothing new, as simply calling LOAD with an output argument does exactly what the description describes:
S = load(...)
creates a structure with all of the contents of the .MAT file. It is much simpler and more efficient to read the MATLAB documentation and use existing MATLAB functions.
The simple solution is to use the normal "save" function. The trick is to load by typing: theworkspace=load('theFilename.mat')
Great function to save time!
Thank you very much!
Why not this?:
w = whos;
for a = 1:length(w)
str.(w(a).name) = eval(w(a).name);
end
Thanks for this function. It would be nice if structure fields where sorted in somehow, e.g.:
WStruct=orderfields(THEWORKSPACE);
BTW, a shorter (but slower) version of the same function would be:
WSVARS = evalin('caller', 'who');
c=cellfun(@(x) evalin('caller',x),WSVARS,'UniformOutput',false);
WStruct2=cell2struct(c,WSVARS,1);
Thanks Jan. I followed your suggestions and now it looks even better.
The function does *not* get the variables of the caller, but of the base workspace. To get the behavior described in the help text, use "WSVARS = evalin('caller', 'who')" insetad of "WSVARS = evalin('base', 'who')". The same for the 2nd EVALIN.
In this line:
eval(strcat('THEWORKSPACE.(WSVARS{wscon})=thisvar;'))
neither EVAL nor STRCAT is needed. Easier and faster:
THEWORKSPACE.(WSVARS{wscon}) = thisvar;