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

问题描述 投票:2回答:2

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

仅是为了将这个问题放在这里,该类可能看起来像这样:

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'

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

matlab class methods get access
2个回答
1
投票

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

另一方面,您可以重载double方法,以使foo = double(ch1)的结果与foo = ch1.value相同。


请注意

我正在重构一些MATLAB旧版软件[...]]

自动导致的排序

尽管如此,这仍需要更改旧版代码中的每一行[...]

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


1
投票

同时,我发现了某种似乎到目前为止的东西,完全可以实现我的目标:使新类继承自MATLAB的标准double类:

© www.soinside.com 2019 - 2024. All rights reserved.