Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab copy constructor

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

like image 388
Dani Avatar asked Oct 29 '08 16:10

Dani


People also ask

How do you copy a function in Matlab?

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.

How do you create a constructor in Matlab?

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).

How do you copy a variable in Matlab?

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.


3 Answers

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.

like image 125
Navan Avatar answered Oct 31 '22 03:10

Navan


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.
like image 42
Mr Fooz Avatar answered Oct 31 '22 03:10

Mr Fooz


You can even use

try
 F.(fns{i}) = rhs.(fns{i});
end

which makes the method more useful

like image 45
Gui Avatar answered Oct 31 '22 03:10

Gui