views:

781

answers:

2

Hi,

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

+3  A: 

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.
Mr Fooz
In the constructor, you should probably test that "rhs" is of type Foo (isa(rhs, 'Foo')) before starting to copy properties.
Marc
A: 

You can even use try F.(fns{i}) = rhs.(fns{i}); end which makes the method more useful

Gui