Matlab类的相关属性,该类可以使用setter存储值
Matlab类属性有以下两个与我的问题相关的限制Matlab类的相关属性,该类可以使用setter存储值,matlab,matlab-class,Matlab,Matlab Class,Matlab类属性有以下两个与我的问题相关的限制 依赖属性不能存储值 属性的setter(没有指定属性的普通属性、访问说明符等)无法访问其他属性 在我的场景中,我需要一个变通方法,允许我拥有一个也可以存储值的从属属性。对另一个属性的依赖仅适用于条件语句,而不适用于用另一个属性本身赋值。下面给出的代码片段说明了这个场景,这也是我的要求,Matlab不允许 classdef foo properties a b end properties (Dependent = true)
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
以上有什么解决方法吗?首先,您肯定可以让一个属性集函数访问另一个属性的值,这不是完全推荐的,因为其他属性的有效性是未知的,尤其是在对象创建期间。这将发出mlint警告。我还认为,如果setter用于从属属性,那么这个mlint警告就不存在 要执行您正在尝试的操作(“在依赖属性中存储”值),您可以为
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
设置为非依赖属性,并定义一个自定义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
首先,您肯定可以让属性集函数访问另一个属性的值,但这不是完全推荐的,因为其他属性的有效性是未知的,尤其是在对象创建期间。这将发出mlint警告。我还认为,如果setter用于从属属性,那么这个mlint警告就不存在 要执行您正在尝试的操作(“在依赖属性中存储”值),您可以为
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
设置为非依赖属性,并定义一个自定义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