Matlab:保存对象的新实例

时间:2017-03-01 12:17:01

标签: matlab class object

说我有以下内容:

classdef Classname
    properties
        property1
    end

    methods
        function a = Classname
        a.property1 = '          ';
        end

        function new = change(a,k)
        a.property1(k) = '!';
        new = a.property1;
        end
    end
end

现在当我使用a = Classname在控制台中运行它然后运行函数change(a,2)时,我得到的输出是:(为了清晰起见而放入撇号而不是输出的一部分)

ans = 
' !        '

当我输入ans.property1时,我得到与上面相同的输出,这是预期的,但是当我输入a.property1时,我只输出原始电路板,即' '。< / p>

我的问题是,如何让a.property1显示当前保存的属性1,以便输出' ! '

1 个答案:

答案 0 :(得分:1)

通过句柄类

的解决方案

正如汤姆在评论中指出的那样,你可以简单地让你的Classname班成为handle班的一个子类:

classdef Classname < handle
    properties
        property1
    end

    methods
        function a = Classname
            a.property1 = '          ';
        end

        function new = change(a,k)
            a.property1(k) = '!';
            new = a.property1;
        end
    end
end

现在,您的示例提供了所需的行为:

a = Classname;
change(a,2);  % Or a.change(2);
a.property1

给出:

ans =

 !        

替代

如果您不想使用句柄类,可以按如下方式重新制定change方法,创建并返回班级的新实例:

classdef Classname
    properties
        property1
    end

    methods
        function a = Classname
            a.property1 = '          ';
        end

        function a_new = change(a,k)
            a_new = a;
            a_new.property1(k) = '!';
        end
    end
end

现在的例子

a = Classname;
a = change(a,2);  % Or a = a.change(2);
a.property1

给出:

ans =

 !        
相关问题