【问题标题】:Why does MATLAB 'forget' updates to variables inside objects? [duplicate]为什么 MATLAB 会“忘记”对对象内部变量的更新? [复制]
【发布时间】:2015-11-04 01:12:19
【问题描述】:

如果我有一个带有

的 MATLAB 类 MyClass
classdef MyClass 

    properties
        myArray
    end

    methods

        function update(obj, i)
            obj.myArray[i] = i*5;
        end
end

我用

调用更新函数
myClass.update(i)

myArray 对象在 i 递增时不会“记住”更新,并且我得到一个空属性。 IE。我的数组 = []

但是,如果我将函数定义如下

classdef MyClass 

    properties
        myArray
    end

    methods

        function out = update(obj, i)
            out = i*5;
        end
end

并调用更新函数

myClass.myArray[i] = update(i)

会记住对 myArray 属性的更新。 IE。 IE。 myArray = [5, 10, 15, 20, 25]

那么这里发生了什么?...在​​所有其他语言中,这将按预期工作,似乎这里有一些 MATLAB 特定的奇怪范围/引用。有人知道发生了什么吗?

【问题讨论】:

  • 您在此处粘贴的代码存在语法错误。

标签: matlab


【解决方案1】:
classdef MyClass 

这定义了一个值类。将值类视为不可变的:值类的成员函数应返回值类的新实例。

你想要一个句柄类,它使用语法声明

classsdef MyClass < handle

请参阅here 了解更多信息。

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2015-03-05
    • 2019-03-01
    相关资源
    最近更新 更多