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
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 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