File Exchange

image thumbnail

Save Workspace to Struct

version (1.56 KB) by Andres
This function allows to save all the variables from the current workspace into a struct array


Updated 19 Apr 2012

View Version History

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.

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

theworkspace =

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

Cite As

Andres (2021). Save Workspace to Struct (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (11)

Melih Ayyildiz

Isabelle Viegas

Bob Sherunkle

Cobeldick, you da real MVP.

Stephen Cobeldick

@Adrien Peyrache: because using EVAL is pointless and slow, just like ASSIGNIN is:

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!

Adrien Peyrache

Why not this?:
w = whos;

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


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


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

MATLAB Release Compatibility
Created with R2011a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!