可以使用 setter 存储值的 Matlab class 的相关属性

Dependent properties of Matlab class that can store values using setters

Matlab class 属性有以下两个与我的问题相关的限制,

  1. 依赖属性不能存储值
  2. setter 对于属性(没有指定属性、访问说明符等的普通属性)无法访问其他属性。

在我的场景中,我需要一个解决方法,它可以让我有一个依赖 属性 也可以存储值。对另一个 属性 的依赖仅适用于条件语句,而不是将其值分配给另一个 属性 本身。下面给出的代码片段说明了这种情况,这也是我要求Matlab不允许的。

classdef foo
properties
    a
    b
end
properties (Dependent = true)
    c
end
methods
    function this = foo(c_init)
        a = 1;
        b = 1;
        this.c = c_init;
    end
    function this = set.c(this,value)
        if b==1
            c = value;
        else
            c = 1;
        end
    end
    function value = get.c(this)
        value = this.c;
    end
end
end

是否有解决上述问题的方法?

首先,您绝对可以让 属性 set 函数访问另一个 属性 的值,只是不完全推荐,因为另一个 属性 的有效性未知特别是在对象创建期间。这将发出 mlint 警告。此外,我 相信 如果 setter 是针对受抚养人 属性,则不存在此 mlint 警告。

要执行您正在尝试的操作("store" Dependent 属性 中的一个值),您可以为 c 创建一个 "shadow" 属性这是私有的,用于存储 c 的基础值。在下面的示例中,我使用 c_ 和下划线来表示它是阴影 属性.

 classdef foo
    properties
        a
        b
    end

    properties (Dependent = true)
        c
    end

    properties (Access = 'private')
        c_
    end

    methods
        function this = foo(c_init)
            this.a = 1;
            this.b = 1;
            this.c_ = c_init;
        end

        function this = set.c(this, value)
            if this.b ~= 1
                value = 1;
            end

            this.c_ = value;
        end

        function value = get.c(this)
            value = this.c_;
        end
    end
end

此外,我不完全确定您的 post 是否是您尝试做的事情的过度简化版本,但对于您提供的示例,您可以很容易地使 c 不是依赖属性,只是定义一个自定义setter。

classdef foo
    properties
        a
        b
        c
    end

    methods
        function this = foo(c_init)
            this.a = 1;
            this.b = 1;
            this.c = c_init;
        end

        function this = set.c(this, value)
            if this.b ~= 1
                value = 1;
            end

            this.c = value;
        end
    end
end