How can I copy the properties of a class object into another in my script in MATLAB 7.12 (R2011a) ?

23 views (last 30 days)
I use a MATLAB script to set properties of Simulink solver for my model. The script looks as below:
%%Create obj1 config set
obj1 = Simulink.ConfigSet;
obj1.get_param('Solver')
%%Set obj2 equal to obj1
obj2 = obj1;
obj1.get_param('Solver')
%%Set Solver of obj2 to FixedStepDiscrete
obj2.set_param('Solver','FixedStepDiscrete')
%%Display Solver after changing of obj2 solver
disp('After setting obj2 solver to a new one:')
obj2.get_param('Solver')
In the code above, using assignment 'obj2 = obj1', I expect that the properties of obj1 are copied into obj2 and can be changed independently therafter.
But, thats not the case. 'obj2' reflects the properties that it obtained from 'obj1'.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 29 Aug 2011
In the MATLAB scripit, the assignment 'obj2 = obj1', given 'obj1' is a class object is an assignment by reference. This is analogous to assignment prperty in Java or any other object oriented language.
In order to copy the properties of a class object using MATLAB script, you have to use the COPY method to copy the properties of the original object. Hence, change the script as shown below:
%%Create obj1 config set
obj1 = Simulink.ConfigSet;
obj1.get_param('Solver')
%%Set obj2 equal to obj1
obj2 = copy(obj1);
obj1.get_param('Solver')
%%Set Solver of obj2 to FixedStepDiscrete
obj2.set_param('Solver','FixedStepDiscrete')
%%Display Solver after changing of obj2 solver
disp('After setting obj2 solver to a new one:')
obj2.get_param('Solver')
The assignment 'obj2 = copy(obj1)' creates a copy of 'obj1' in 'obj2' which can be changed independently.

More Answers (0)

Products


Release

R2011a

Community Treasure Hunt

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

Start Hunting!