Doug's MATLAB Video Tutorials
October 12th, 2010
Writing out your workspace variables as a script with Simulink.saveVars
I almost never use Simulink, so I never saw this function before (requires Simulink).
Try this at the command line:
a = 1;
b = 2.5;
c = 'A string';
d = {a, b, c};
Simulink.saveVars('MyVars');
It produces a file like this:
% -------------------------------------------------------------------
% MATLAB file generated by Simulink.saveVars on 27-Sep-2010 13:52:16
% MATLAB version: 7.11.0.584 (R2010b)
% -------------------------------------------------------------------
a = 1;
b = 2.5;
c = 'A string';
d = cell(1, 3);
d{1} = 1;
d{2} = 2.5;
d{3} = 'A string';
I can see something like this being a lot more transparent than saving variables to a .mat file. for small variables. For example, if you want to take your current workspace and use it as the basis for a script. This script can be modified easily, and you can even call saveVars again to write new or updated data into your modified script.
It’s quite configurable. For instance, you can specify the size threshold above which large variables will just be saved to a .MAT file instead of written to the script (the script automatically loads the .MAT file). You can even control the maximum width of the generated code.
You might find that it will gives me a more readable script than simply loading a .mat file. People reading your code will see more of what you are doing. This helps with readability.
What kinds of uses can you think of for this cool function?
By
Doug Hull
Doug first used MATLAB in 1994, could not figure it out until he got some help in 1995. He is now dedicated to making sure that no one else wastes a year of their life not knowing MATLAB like he did.
18:47 UTC |
Posted in Level: Basic, Topic: Cool feature |
Permalink |
4 Comments »
You can follow any responses to this entry through the RSS 2.0 feed.
You can skip to the end and leave a response. Pinging is currently not allowed.
Leave a Reply
|
This looks to be 2010b only (at least … it doesn’t seem to work on 2009a!)
Must get that update done soon! :)
@Yasin Abbas – Simulink.saveVars was introduced in R2009b. It is mentioned in the Data Management Section of the release notes.
Over a year ago, I have submitted something similar to MATLAB central – have a look at
http://www.mathworks.com/matlabcentral/fileexchange/24447-generate-m-file-code-for-any-matlab-variable
Except for very large numerical arrays, saving struct or cell variables as .m file code is very often a good idea.
I use this functionality to create commands for regenerating icons that I use for my GUI. Toolbar icons accept a 16x16x3 CData. I have icon graphics, but I don’t want to always load it for a graphics file (or even a MAT file). So I use Simulink.saveVars to create the command, and put that bit of code in one of the subfunctions in my MATLAB file.