matlab - 返回特定属性的默认 get 方法 - MATLAB

标签 matlab class methods get

我正在重构一些 MATLAB 遗留软件,涉及在广泛的测试中获得的数据。我正在尝试创建一个包含每个单独 channel 的数据以及一些额外信息(例如其物理单位)的类。

只是为了将这个问题放在这里,该类可能如下所示:

classdef Channel < handle
    properties (Access = 'private')
        prvValue, prvUnits;
    end

    properties (Dependent)
        value, units;
    end

    methods
        function this = Channel(value, units)
            this.value = value;
            this.units = units;
        end

        function set.value(this, value)
            this.prvValue = value;
        end

        function out = get.value(this)
            out = this.prvValue;
        end

        function set.units(this, units)
            this.prvUnits = units;
        end

        function out = get.units(this)
            out = this.prvUnits;
        end                  
    end
end

您可以使用以下内容创建此类的对象:

> ch1 = Channel([1:10], 'm');

并通过以下方式访问其依赖属性:

>> ch1.value

ans =

     1     2     3     4     5     6     7     8     9    10

>> ch1.units

ans =

    'm'

尽管如此,这仍然需要将访问数据的遗留代码中的每一行从“ch1”之类的内容更改为“ch1.value”。

现在我的问题是:有没有办法定义一种返回类的特定属性(在本例中为“值”)的“默认获取方法”?换句话说,行为如下:

>> ch1

ans =

     1     2     3     4     5     6     7     8     9    10

>> ch1.units

ans =

    'm'

欢迎任何帮助。非常感谢。

最佳答案

不,ch1 本身就是对象。如果您单独键入 ch1(通过重载 display 方法),则可以让 MATLAB 输出“ans = 1 2 3 ...”,但这实际上不会分配该值对 ans 的值(value)。特别是,您无法更改 foo = ch1 的结果,foo 将始终是对象本身。

另一方面,您可以重载 double 方法,这样 foo = double(ch1) 的结果与 foo = ch1.value.


请注意

I'm in the process of refactoring some MATLAB legacy software [...]

有点自动导致

This would nonetheless require to change every single line in the legacy code [...]

重构代码涉及大量重写。如果您不想更改太多代码,请减少重构的侵入性。不要将普通数组更改为复杂对象。

关于matlab - 返回特定属性的默认 get 方法 - MATLAB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60968076/

相关文章:

matlab - 快速移位/快速移位

matlab - 在 numpy 中实现与 matlab 相同的随机数

matlab - 使用 MATLAB 实现 SIFT 和 SURF 特征提取

python - 使用 Python API 表示 Google Drive 文件夹的文件和文件夹树

java - 如何在 Java 中实现许多类通用的自定义方法?

java - 在 Java String 方法中获取 int 变量

matlab - 计算图像中的水平和垂直线

html - 如何将此表格和按钮放在图像旁边(图像右侧)

c++ - vector 消失

c# - 从 "Form"类调用 "A"类方法而不添加对 "Form"类的引用