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

42 次查看(过去 30 天)
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.

采纳的回答

MathWorks Support Team
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 个评论
Stephen23
Stephen23 2018-9-4
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 2019-9-25
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Debugging and Analysis 的更多信息

产品


版本

R2009a

Community Treasure Hunt

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

Start Hunting!

Translated by