MATLAB: How to find all objects with a specific Property in the workspace, in MATLAB R2011a (7.12)

handleinstanceMATLAB

My workspace contains a set of objects of different Classes (all derived from Handle), some of which contain a certain Property. I desire to find the objects which contain that particular Property only.

Best Answer

The following code demonstrates how to accomplish this functionality. Suppose there are two classes defined as follows:
classdef testClassA < dynamicprops
properties
propA
end
end
classdef testClassB < handle
properties
propB
end
end
With those two classes, use the following script to look up all the objects instantiated from a given class. One needs to specify in the script the name of Class, whose objects will be searched for a particular Property.
A1 = testClassA;
A2 = testClassA;
A3 = testClassB;
% Test Property which will be searched for
propName = 'newPropA';
A2.addprop(propName);
% Objects of Class, or Subclass, of 'className' will be found
className = 'testClassA';
wrkSpcVars = who;
isObj = false(size(wrkSpcVars));
for idx = 1:length(wrkSpcVars)
isObj(idx) = isa( eval(wrkSpcVars{idx}), className );
end
% Find the corresponding objects
myObjs = cellfun( @eval , wrkSpcVars(isObj), 'UniformOutput', false);
% Find objects with desired Property from the above list
hasProp = cellfun( @(x) ismember( propName, properties(x) ) , myObjs );
% The result is stored in propObjs
propObjs = myObjs(hasProp);
Related Question