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

40 ビュー (過去 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
MathWorks Support Team 2018 年 9 月 4 日
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 Center および File ExchangeDebugging and Analysis についてさらに検索

製品


リリース

R2009a

Community Treasure Hunt

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

Start Hunting!

Translated by