Sometimes I want to work with a variable from the base workspace, but inside a function. This problem arose for me when I wrote a gui tool, that occasionally would need a variable from the base workspace. I realized a tool was needed to put up a dialogue box that would list all of the variables in the base work space, and allow you to choose one to bring into the function workspace.
uigetvar is such a tool. It allows you to specify a list of classes to show in the uigetvar box as a restriction so if you only wish to see the 'char' class variables, you can easily do so.
Once I wrote uigetvar, it became logical to define the counterpart operator, putvar. The putvar tool allows you to assign a variable from a function workspace directly into the base workspace. I can envision this tool having value in one of two ways.
First, during a debugging session, one might wish to save one or more variables from the function workspace into the base workspace. This way those variables will still exist after the debugger has terminated and you have exited from the function.
A second use for this tool is as an alternative way to return a variable (or variables) from a function, possibly a GUI, during the operation of that GUI.
As an example of the operation of this code, here is a simple function that uses putvar. Note that you can provide either a variable in the workspace as input, or the name itself of the variable. Either mode of operation works.
A = 3;
B = 23;
C = pi/2;
D = 'The quick brown fox jumps over the lazy dog';
Save the function testputvar.m on your search path.
Then at the command line in MATLAB, try this. First, clear your workspace. Clear ensures that no variables exist initially in the base workspace. Then run the function testputvar, and finally execute the who command, all at the command line.
Your variables are:
A C D
The output from who tells it all. Inside the function testputvar, we had defined four variables, A, B, C, and D. But after testputvar terminates, its variables will fall into the bit bucket, disappearing into limbo. The putvar call inside testputvar ensures that the variables A, C, and D are returned into the base workspace, yet no return arguments were provided.
In the event that you wanted to assign all of the variables from the caller workspace, just do this inside your function...
W = who;
I had considered wrapping a GUI around putvar, probably called uiputvar, but I don't see much benefit there, whereas the uigetvar tool truly does need to be a GUI.
John D'Errico (2022). putvar, uigetvar (https://www.mathworks.com/matlabcentral/fileexchange/27106-putvar-uigetvar), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform CompatibilityWindows macOS Linux
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!