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

42 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 4 de Sept. de 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 comentarios
Stephen23
Stephen23 el 4 de Sept. de 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 el 25 de Sept. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Debugging and Analysis en Help Center y File Exchange.

Productos


Versión

R2009a

Community Treasure Hunt

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

Start Hunting!

Translated by