Code covered by the BSD License  

Highlights from
Save Workspace to Struct

Be the first to rate this file! 25 Downloads (last 30 days) File Size: 1.56 KB File ID: #36257

Save Workspace to Struct



18 Apr 2012 (Updated )

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

| Watch this File

File Information

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.

 c={'cell1', 'cell2', 'cell3'}

 theworkspace =
     a: 'LALALA'
     b: [1x22 double]
     c: {'cell1' 'cell2' 'cell3'}
     d: 768
     e: [3x3 logical]

MATLAB release MATLAB 7.12 (R2011a)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (4)
29 Apr 2014 Adrien peyrache

Why not this?:
w = whos;

for a = 1:length(w)
str.(w(a).name) = eval(w(a).name);

14 Aug 2012 Óscar

Thanks for this function. It would be nice if structure fields where sorted in somehow, e.g.:

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

19 Apr 2012 Andres

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

19 Apr 2012 Jan Simon

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:
neither EVAL nor STRCAT is needed. Easier and faster:
THEWORKSPACE.(WSVARS{wscon}) = thisvar;

19 Apr 2012

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;

Contact us