如何修改 Matlab 对象的属性 [英] How to modify properties of a Matlab Object

查看:14
本文介绍了如何修改 Matlab 对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 MATLAB 类,例如:

I've created a MATLAB class, something like:

classdef myclass

  properties
      x_array = [];
  end

  methods
    function increment(obj,value)
       obj.x_array = [obj.x_array ; value);
    end
  end
end

问题是,当我调用 increment() 函数时,属性 x_array 永远不会被修改:例如:

The problem is, the property x_array is never modified when I invoke the increment() function: ex:

>>s = myclass
>>increment(s,5)

>>s.x_array
ans = []

我做了一些研究,得出的结论是,这是因为 MATLAB 对对象使用了 Lazy Copy,让我的类继承 HANDLE 类应该可以解决这个问题,但它没有,有没有人知道为什么会发生这种情况?如果扩展句柄类是解决方案,这不是正确的方法吗:

I did some research, and I reached a conclusion that this is because of MATLAB using Lazy Copy for objects, making my class inherit the HANDLE class should have solved this, but it didn't, does anybody know why this is happening? And if extending the handle class is indeen the solution, isn't this the right way to do it:

classdef myclass < handle

或者有什么额外的步骤吗?

or are there any extra steps?

推荐答案

这类似于这个问题.简而言之,您应该做的就是从句柄类继承.

This is similar to this question. In short all you should have to do is inherit from handle class.

快速示例

文件 myclass.m 的内容

Contents of file myclass.m

classdef myclass<handle
    properties
        x_array = []
    end
    methods
        function obj=increment(obj,val)
            obj.x_array=[obj.x_array val];
        end
    end
end

现在在 Matlab 命令提示符下,您可以执行以下操作

Now from the Matlab command prompt, you can do the following

>> s=myclass;
>> s.increment(5)
>> s.increment(6)
>> s

s = 

myclass handle

properties:
    x_array: [5 6]

lists of methods, events, superclasses

这篇关于如何修改 Matlab 对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆