Matlab copy constructor

六月ゝ 毕业季﹏ 提交于 2019-12-03 07:38:08

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.

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.

Gui

You can even use

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

which makes the method more useful

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!