How to find values of properties of variables/objects in files?

13 views (last 30 days)
I have a matlab file, let's call i dataset.mat. When loading dataset.mat into workspace, it contains several variables, all these variables are objects defined as a class. Let's call these variables:
varObj1 varObj2 varObj3 ... varObjN
Now all these variables contain the properties that are defined in the object class. Let's say that varObj1 has the properties:
prop1 prop2 prop3 ... propM
All of these properties hold some value, either numbers, text or arrays.
The question is now: How to extract the values of all these properties in some automated way? I.e. make some sort of script that goes into each varObj and extracts each property of that object to another file, something like:
newFile1 = varObj1.prop1 newFile2 = varObj1.prop2 ... newFileNM = varObjN.propM
I have lists of all the filenames of the varObj's and all the prop's.

Answers (1)

Guillaume
Guillaume on 15 May 2015
Edited: Guillaume on 15 May 2015
Use the metaclass information to get the list of properties and query them:
mc = metaclass(varObj); %get meta.class associated with object
mps = mc.PropertyList; %array of meta.properties (description of all the properties of the object, including private properties)
propnames = {mps.Name};
publicpropnames = propnames(strcmp({mps.GetAccess}, 'public'))
publicpropvalues = cellfun(@(pname) varObj.(pname), publicpropnames, 'UniformOutput', false)
  2 Comments
uffeaf
uffeaf on 16 May 2015
Thanks, the code works fine, but I'm stuck with the same problem as before I wrote this question. The varObj's are taken from the list varObjList, so the last line of the code would, in case we are looking at the i'th element of that list, be:
publicpropvalues = cellfun(@(pname) varObjList(i).(pname), publicpropnames, 'UniformOutput', false)
And so there's another error message.
To rephrase my question more precisely, given lists varObjList and propList, is there a way to find the values in the properties like:
newFile = varObjList(i).propList(j)
picking out the value of the j'th property of the i'th varObj?
Guillaume
Guillaume on 16 May 2015
I'm not entirely sure what you're asking anymore. If you're asking how to extract the property of an object given the name of the property as string, then simply enclose the string variable in brackets:
varobj = someobject;
propname = 'somepropname';
propvalue = someobject.(propvalue)
If you also have the name of the object as a string, then the only way is to use eval:
objname = 'varobj';
propname = 'somepropname';
propvalue = eval(sprintf('%s.%s', objname, propname))
If you're asking something else, give a clearer example.

Sign in to comment.

Categories

Find more on Environment and Settings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!