2

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.

Wolfie
  • 27,562
  • 7
  • 28
  • 55
Sack11
  • 153
  • 11

1 Answers1

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
sco1
  • 12,154
  • 5
  • 26
  • 48
  • 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. – Sack11 Feb 23 '18 at 08:14
  • 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. – Wolfie Feb 23 '18 at 10:18
  • See [this answer](https://stackoverflow.com/questions/34676687/how-can-one-clear-all-the-variables-but-the-ones-wanted/34676847#34676847) for clearing variables except for those matching a regex. – sco1 Feb 23 '18 at 10:45