如何在面向对象的Matlab中定义派生属性

Dav*_*ave 5 oop matlab

我想要一个我可以访问的只读字段fv=object.field,但返回的值是从对象的其他字段计算的(即返回值满足fv==f(object.field2)).

所需的功能与propertyPython中的function/decorator 相同.

我记得看到一个参考,通过设置properties块的参数这是可能的,但Matlab OOP文档是如此分散,我再也找不到它.

Pur*_*uit 5

这称为"依赖"属性.使用派生属性的类的快速示例如下:

classdef dependent_properties_example < handle       %Note: Deriving from handle is not required for this example.  It's just how I always use classes.
    properties (Dependent = true, SetAccess = private)
        derivedProp
    end
    properties (SetAccess = public, GetAccess = public)
        normalProp1 = 0;
        normalProp2 = 0;
    end
    methods
        function out = get.derivedProp(self)
            out = self.normalProp1 + self.normalProp2;
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

定义了这个类,我们现在可以运行:

>> x = dependent_properties_example;
>> x.normalProp1 = 3;
>> x.normalProp2 = 10;
>> x
x = 
  dependent_properties_example handle

  Properties:
    derivedProp: 13
    normalProp1: 3
    normalProp2: 10
Run Code Online (Sandbox Code Playgroud)