【问题标题】:How to change the property of an instance in MatlabMatlab中如何改变实例的属性
【发布时间】:2013-02-23 18:16:07
【问题描述】:

我是 MATLAB 新手,我想编写一个类的方法来更改该对象的属性:

classdef Foo

  properties
    a = 6;
  end
  methods
    function obj = Foo()
    end

    function change(obj,bar)
      obj.a = bar
    end
  end
end




foo = Foo()

foo.change(7) //here I am trying to change the property to 7

原来属性还是6。

【问题讨论】:

    标签: matlab matlab-class


    【解决方案1】:

    MATLAB 在 值类句柄类 之间有所区别。值类的实例在赋值上被隐式复制(因此表现得像普通的 MATLAB 矩阵),句柄类的实例不是(因此表现得像其他 OOP 语言中的实例)。

    因此,您必须为值类返回修改后的对象:

    classdef ValueClass
        properties
            a = 6;
        end
        methods
            function this = change(this, v)
                this.a = v;
            end
       end
    end
    

    这样称呼它:

    value = ValueClass();
    value = value.change(23);
    value.a
    

    或者,您可以从 handle 类派生您的类:

    classdef HandleClass < handle
        properties
            a = 6;
        end
        methods
            function change(this, v)
                this.a = v;
            end
       end
    end
    

    然后这样称呼它:

    h = HandleClass();
    h.change(23);
    h.a
    

    MATLAB documentation 中有更多信息。

    【讨论】:

    • 史诗般的答案,对我来说完全有意义,即使它不是那么优雅
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 2020-02-19
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    相关资源
    最近更新 更多