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

查看:209
本文介绍了如何修改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对对象使用了惰性复制,使得我的类继承了HANDLE类应该解决了这个问题,但是没有,有人知道为什么会这样吗?而且如果扩展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

还是还有其他步骤?

推荐答案

这类似于此问题.简而言之,您需要做的就是从handle类继承.

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天全站免登陆