【发布时间】:2020-02-19 04:17:59
【问题描述】:
我有一个问题,我想对一些物理现象进行建模。这种现象由几个阶段组成,每个阶段都可能有自己的控制方程(动力学以及变量数量、约束、变量边界等)。为了对这个阶段的属性进行分组,我编写了一个类phase。此类的一个实例具有一个名为nVars 的属性,即控制方程中的变量数(因此在此类的实例中可能会有所不同)。
现在,假设我想要这个类的另一个属性,称为boundaries。因为我需要以非常具体的方式制定变量边界,所以我还创建了一个类boundaries。这个类有属性lower和upper;变量的下界和上界。但是,这些上下边界的长度取决于phase 实例的nVars。
在最一般的情况下,下边界都是-Inf,上边界都是Inf。因此,我想将boundaries 属性lower 和upper 的值分别默认为-Inf * ones([1 nVars]) 和Inf * ones([1 nVars])。现在,我的问题是:如何使类属性的默认值依赖于变量(在这种情况下为nVars)。
我的第一次尝试:
classdef phase
properties
nVars(1, 1) double
boundaries boundaries
end
methods
function obj = phase(nVars)
%Some constructor method
obj.nVars = nVars;
obj.boundaries = boundaries(obj);
end
end
end
classdef boundaries
properties
parent phase
lower = -Inf * ones([1 parent.nVars]);
upper = Inf * ones([1 parent.nVars]);
end
methods
function obj = boundaries(parent)
%Some constructor method
obj.parent = parent;
end
end
end
或者,我尝试通过以下方式默认边界类的属性:
classdef boundaries
properties
parent phase
lower(1, parent.nVars) double = -Inf;
upper(1, parent.nVars) double = Inf;
end
methods
function obj = boundaries(parent)
%Some constructor method
obj.parent = parent;
end
end
end
谁能帮助我理解如何根据变量分配这些默认值?
【问题讨论】:
-
或许你可以定义为
lower(1,:) double = -Inf,在boundaries的构造函数中初始化为合适的大小,然后添加一个属性监听器,检查lower和@987654343的大小@ 并使用obj.parent.nVars验证它(仅在调用构造函数后可用)。有关属性侦听器的信息,请参阅 here。 -
您的问题的答案在您的标题中:“在构造实例时设置的变量?” ... 在
boundaries对象的 constructor 中分配默认值。它与简单的 classdef 默认值一样好用,您可以在上面编写各种输入检查代码。
标签: matlab oop properties instance