MATLAB: How to add Dynamic Properties to the value class in MATLAB 8.0 (R2012b)

addpropdynamicpropshandleMATLABstructuresvalue

I have a Value Class 'myClass' and I would like to add properties to an instance of this class, the names of which are available only at the run time. Hence I would like to add these properties Dynamically to an instance of the class myClass.
I am not able to Sub-Class from DYNAMICPROPS because that would make my class a handle class.

Best Answer

In order to have dynamically added properties for the instances of your value class, we would recommend that you have a structure (a variable of type Struct) as one of the properties of your class and then add fields to this structure dynamically (either during the construction of the objects or there after). You can add fields to the structure dynamically using a feature in the MATLAB Language called 'Dynamic Field access' for structures.
Please refer to the documentation page here:
A quick example is provided in this solution, myClass.m, (See attached) that implements a constructor that takes two property name and value pairs that are added to the object during its construction. myClass also has a function called addprops that adds more fields to this structure. Here is how the output looks like at the MATLAB Command Prompt.
>> myDynamicProp1 = 'prop1';
>> myDynamicProp2 = 'prop2';
>> obj = myClass(myDynamicProp1, 5, myDynamicProp2, 7.8)
obj =
myClass
Properties:
myStruct: [1x1 struct]
Methods
>> newObj = obj.addprop('prop3', 'Hello')
newObj =
myClass
Properties:
myStruct: [1x1 struct]
Methods
>> newObj.myStruct
ans =
prop1: 5
prop2: 7.8000
prop3: 'Hello'
>>
The MATLAB script file tsTest.m (see attached) has the same commands as shown above.