How do I find all the variables of a given class in the MATLAB workspace?

57 views (last 30 days)
I would like to be able to find all the variables of a given class in MATLAB. The class could be a built-in or user-defined.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 4 Sep 2018
A function to find all the variables of a given class is not available in MATLAB.
As a workaround, one can use the following code to display all the variables of class "ClassName" in the Command Window:
s = whos; % Looks for all variables
data_collector = zeros(size(s)); % Pre-allocation
disp('List of ClassName Type variables')
for i = 1:length(s)
k = s(i).class;
data_collector(i) = strcmp(k,'ClassName');
if data_collector(i) == 1 % Write variable name in the Command Window
disp(s(i).name) % Display data
end
end
Or,
s = whos;
% find the objects with the type 'ClassName' from the workspace:
matches= strcmp({s.class}, 'ClassName');
my_variables = {s(matches).name}
This also applies to Simulnk Enumeration class. For example:
>> Simulink.defineIntEnumType('a',{'b','c','d'},[1,2,3],'DefaultValue','b','DataScope','Imported','AddClassNameToEnumNames',false)
>> s = a.b;
>> t = 1;
>> vars = whos;
>> idx = ismember({vars.class}, 'a');
>> vars_double = vars(idx);
Then, "vars_double" will only include the variables "s".
  2 Comments
Stephen23
Stephen23 on 4 Sep 2018
A warning for anyone interested in writing efficient code:
"Avoid functions that query the state of MATLAB such as inputname, which, whos, exist(var), and dbstack. Run-time introspection is computationally expensive."
Steven Lord
Steven Lord on 25 Sep 2019
That sounds like a reasonable enhancement request to file with Technical Support using the telephone icon in the upper-right corner of this page. In addition to telling Technical Support what you want them to enter into the enhancement database (allow who and whos to return only variables of a specific class) it would be useful to tell them why you want that and/or how you would use that functionality. That can help the development team understand how you expect the feature to behave and provide some additional motivation when they're prioritizing development work.

Sign in to comment.

More Answers (0)

Categories

Find more on Debugging and Analysis in Help Center and File Exchange

Products


Release

R2009a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!