tags:

views:

50

answers:

1

Say I have a MATLAB object defined in a class file

classdef foo

   properties
      bar
   end

end

And I create a foo object

myfoo = foo();

Now I want to add another field to foo dynamically. What I want is

myfoo.newfield = 42;

but this will throw an error.

I know there is a way to dynamically add a field/property to a MATLAB object but I can't remember it or find it easily in the help. Anyone know the syntax?

+2  A: 

Ok, found it. But it's not general, only subclasses of the dynamicprops class implement it. This is what I remember coming across. So I suspect the general answer to this question is you can't do it.

Any class that is a subclass of the dynamicprops class (which is itself a subclass of the handle class) can define dynamic properties using the addprop method. The syntax is:

P = addprop(H,'PropertyName')
Marc
RjOllos
I don't think there is a lot of robustness to begin with. The limit on the number and names of properties is not nearly as significant as strong typing, which matlab doesn't have. What do you lose by dynamically adding a field -- this won't break any existing code that doesn't know about the field. But if "square" is supposed to be a "Shape," you can say obj.square = 3 and break existing code that relies on "square" being a "Shape."The reason to do this would be to change a class that is already in memory without having to clear and reload all instances of that class.
Marc