View License

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

» Watch video

Highlights from
Save Workspace to Struct

3.7 | 3 ratings Rate this file 16 Downloads (last 30 days) File Size: 1.56 KB File ID: #36257 Version: 1.2

Save Workspace to Struct


Andres (view profile)


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 (7)
13 Sep 2016 Felix

Felix (view profile)

03 May 2016 Mdaatniel

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

12 Nov 2015 PT

PT (view profile)

Great function to save time!
Thank you very much!

29 Apr 2014 Adrien Peyrache

Why not this?:
w = whos;

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

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

Comment only
19 Apr 2012 Andres

Andres (view profile)

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

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

Comment only
19 Apr 2012 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;

Contact us