Search code examples
matlab

List workspace variables in function


In a GUI, I'd like to allow the user to import a value from the workspace. Therefore, I want to show a list of the variables defined in the workspace and let the user select one. Something similar is done, for example, in the cftool for the x- and y- (and z-) data.

However, if I use who within a function, it does not list the variables in the workspace (Note: The following code creates or overwrites the variable mytestvar in your workspace):

function listwsvars()
    assignin('base','mytestvar',1);
    vars = whos('global');

    vars
end

The result is the same if I omit the global argument or use who instead of whos.

Any idea how I can get a list of the variables in the workspace? And in turn, how can I access them?


Solution

  • By default, whos will return the variables in the active workspace (in this case, the function listwsvars). With the global option, it will return the ones in the global workspace. If you have not defined global variables, this will indeed return empty.


    A possible solution is to evaluate the whos command in the base workspace with evalin:

    function listwsvars()
        assignin('base','mytestvar',1);
        vars = evalin('base','whos');
    
        vars
    end
    

    vars is a struct array containing information on all the variables available in the base workspace.