Code covered by the BSD License  

Highlights from
Save Workspace to Struct

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

Save Workspace to Struct

by

 

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
Description

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]

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

14 Aug 2012 Óscar

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

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

Updates
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