File Exchange

image thumbnail

Save Workspace to Struct

version 1.2 (1.56 KB) by

This function allows to save all the variables from the current workspace into a struct array

3.66667
3 Ratings

14 Downloads

Updated

View License

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]

Comments and Ratings (7)

Felix

Felix (view profile)

Mdaatniel

The simple solution is to use the normal "save" function. The trick is to load by typing: theworkspace=load('theFilename.mat')

PT

PT (view profile)

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

Óscar

Óscar (view profile)

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);

Andres

Andres (view profile)

Thanks Jan. I followed your suggestions and now it looks even better.

Jan Simon

Jan Simon (view profile)

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;

Updates

1.2

Two little corrections, thanks to Jan Simon, this way the variables saved are not necessarily from the base workspace but from the current (caller) workspace:
WSVARS = evalin('caller', 'who');
THEWORKSPACE.(WSVARS{wscon}) = thisvar;

MATLAB Release
MATLAB 7.12 (R2011a)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video