1

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.

chappjc
  • 30,359
  • 6
  • 75
  • 132
Hannes Ovrén
  • 21,229
  • 9
  • 65
  • 75

3 Answers3

3

value = getfield(struct, 'field')

Oli
  • 15,935
  • 7
  • 50
  • 66
2

You can use:

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

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

JaBe
  • 664
  • 1
  • 8
  • 27
Kavka
  • 4,191
  • 16
  • 33
0
cellfun( @(prop) obj.(prop), properties(obj), 'UniformOutput', false )
Edric
  • 23,676
  • 2
  • 38
  • 40