MATLAB: How do I get the value of a class property given a property name

2.7k Views Asked by At

If I have a class defined as

classdef myclass
  properties
     foo = 3;
     bar = 7;
  end
end

And I want to access property foo I would write

obj = myclass()
obj.foo % Gives me 3

But, if I only have a string representation of the property name, and don't know which property it is how would I do it then? As in the example below:

obj.someFunction('foo')  % or
someFunction(obj, 'foo') % should both give me the value of obj.foo

What I want to do is have a list of properties, iterate through it and get the value for a specific object. It seems like it should be possible, but I failed to find it in the documentation.

3

There are 3 best solutions below

0
On BEST ANSWER

value = getfield(struct, 'field')

0
On

You can use:

obj = myclass();
propName = 'foo';
propValue = obj.(propName);

For more information, see Generating Field Names from Variables and Dot-Parentheses.

3
On
cellfun( @(prop) obj.(prop), properties(obj), 'UniformOutput', false )