Is there a better way to implement copy construcor for matlab for a handle derived class other than adding a constructor with one input and explicitly copying its properties?
obj.property1 = from.property1;
obj.property2 = from.property2;
etc.
Thanks, Dani
B = copy(A) copies each element in the array of handles A to the new array of handles B . The copy method performs a copy according to the following rules: The copy method does not copy Dependent properties. MATLAB® does not call the copy method recursively on any handles contained in property values.
Guidelines for ConstructorsThe constructor has the same name as the class. The constructor can return multiple arguments, but the first output must be the object created. If you do not want to assign the output argument, you can clear the object variable in the constructor (see Output Object Suppressed).
Select the variables, right-click, and then select Duplicate. MATLAB creates a copy of the selected variables. Right-click the variable name, and then select Rename.
There is another easy way to create copies of handle objects by using matlab.mixin.Copyable. If you inherit from this class you will get a copy method which will copy all the properties for you.
classdef YourClass < matlab.mixin.Copyable
...
a = YourClass;
b = copy(a); % b is a copy of a
This copy method creates a copy without calling constructors or set functions of properties. So this should be faster. You can also customize the copy behavior by overriding some methods.
If you want a quick-and-dirty solution that assumes all properties can be copied, take a look at the PROPERTIES function. Here's an example of a class that automatically copies all properties:
classdef Foo < handle
properties
a = 1;
end
methods
function F=Foo(rhs)
if nargin==0
% default constructor
F.a = rand(1);
else
% copy constructor
fns = properties(rhs);
for i=1:length(fns)
F.(fns{i}) = rhs.(fns{i});
end
end
end
end
end
and some test code:
f = Foo(); [f.a Foo(f).a] % should print 2 floats with the same value.
You can even use
try
F.(fns{i}) = rhs.(fns{i});
end
which makes the method more useful
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With