3

Lets say I have 100 variables in Matlab workspace. For example I take 5 variables here:

Matrix
Sum
Addition
Area
Perimeter
Subtraction

...and so forth.

How can I select or filter out a variable name based on some keyword likeAdd or a search term which selects the variable Addition in the workspace. I used the who command as

who -regexp Add 

But this only displays the name of the variable and not its value.

1 Answer 1

2

One of the rare occasions where eval is possibly the most appropriate approach. (gasp)

You can use the functional version (see: Syntax) of who to store the names of the variables that match the regex in a cell array. If you iterate over these names with eval it will behave as if they were being called from the command line, which will display their values if not suppressed.

For example:

Matrix = rand(3);
Sum = rand(3);
Addition = rand(3);
Area = rand(3);
Perimeter = rand(3);
Subtraction = rand(3);
Additional = rand(3);

vars = who('-regexp', '[Aa]dd');
for ii = 1:numel(vars)
    eval(vars{ii})
end

Displays:

Addition =

    0.8143    0.3500    0.6160
    0.2435    0.1966    0.4733
    0.9293    0.2511    0.3517


Additional =

    0.6892    0.0838    0.1524
    0.7482    0.2290    0.8258
    0.4505    0.9133    0.5383
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the response. I do have another question. This displays the values of the variables in the command window. How to get only these variables in the workspace as well, so that it can be clicked and viewed.
They are already in the workspace where they can be clicked and viewed... You could use FilteredVars.(vars{ii})=eval(vars{ii}) to store them in a struct which, when explored in the workspace would only contain your variables. However, note you would be duplicating all those variables in memory, and they would not be linked to the actual values in the workspace.
See this answer for clearing variables except for those matching a regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.