Matlab类的依赖属性,可以使用setter

时间:2016-02-17 20:45:09

标签: matlab matlab-class

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

  1. 附属属性无法存储值
  2. 属性的setter(没有指定属性的正常属性,访问说明符等)无法访问其他属性。
  3. 在我的场景中,我需要一个解决方法,这将允许我有一个依赖属性,也可以存储值。对另一个属性的依赖仅适用于条件语句,而不是用于将其值与其他属性本身分配。下面给出的代码片段说明了这种情况,这也是我对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
    

    以上是否有解决方法?

1 个答案:

答案 0 :(得分:3)

首先,你肯定可以让一个属性集函数访问另一个属性的值,它只是不完全推荐,因为其他属性的有效性是未知的,特别是在对象创建期间。这将发出mlint警告。此外,我相信如果设置者是依赖属性,那么这个mlint警告就不会出现。

要做你正在尝试的事情("存储" Dependent属性中的值),你可以创建一个" shadow" c的属性,它是私有的,用于存储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

此外,我还不完全确定您的帖子是否是您尝试做的过度简化版本,但对于您提供的示例,您可以非常轻松地制作c < strong>不依赖属性,只需定义自定义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