在Matlab中对类get函数返回的数据数组进行寻址



我正试图为以下情况找到一个好的解决方案:

我有一门课:

classdef SomeClass < handle
    properties (Access = private)
        x
    end
    methods
        function x = getX(this)
            x = this.x;
        end
    end
end

x-某个数据数组。我是否有可能像在结构中一样处理数组的某些元素:

struct.x(5)

还是我总是要这样做?:

myClassObj = SomeClass();
x = myClassObj.getX();
x(5)

或者创建一些函数getXAt?

是。像这样寻址是Matlab对象中属性的正常行为。您可以只公开该属性进行读取,而不是使其完全为private

classdef SomeClass < handle
    properties (SetAccess=private)
        x
    end
    methods
        function obj = SomeClass(x)
            obj.x = x;
        end
    end
end

然后,您可以像结构上的字段一样对其进行寻址。

>> sc = SomeClass(1:7);
>> sc.x(5)
ans =
     5
>> 

在Matlab中没有必要总是像在Java中那样制作自己的访问器函数。您可以使用属性独立控制属性的读写访问。如果您想要更复杂的属性访问逻辑,可以使用特殊的function out = get.x(obj)语法定义getter和setter,它们的行为将应用于使用obj.x语法完成的属性访问。

在Matlab中,任何类都是类的数组

因此,你可以这样写你的课:

classdef SomeClass < handle
    properties (Access = private)
        x
    end
    methods (Access=public)        
        function this = SomeClass(x)
            this.x = x;
        end
    end
    methods
        function x = getX(this)                
            x = [this.x];
        end
    end
end

访问方式如下:

s(1)=SomeClass(1)
s(2)=SomeClass(5)
s(3)=SomeClass(6);

s.getX()

ans=

1     5     6

s(2).getX()

ans=

5

最新更新