如何根据在构造实例时设置的实例变量默认大小的 Matlab 实例的 属性?

How do I default a property of a Matlab instance with a size based on an instance variable that is set upon constructing the instance?

我有一个问题,我想模拟一些物理现象。这种现象由几个阶段组成,每个阶段都可能有自己的控制方程(动力学,因此没有变量、约束、变量边界等)。为了对这个阶段的属性进行分组,我写了一个class phase。这个 class 的一个实例有一个 a.o,一个叫做 nVars 的 属性,控制方程中变量的数量(因此可能因这个 class).

现在,假设我想要另一个 属性 用于此 class,称为 boundaries。因为我要求以非常具体的方式制定变量边界,所以我还创建了一个 class boundaries。此 class 具有属性 lowerupper;变量的下边界和上边界。但是,这些下边界和上边界的长度取决于 phase 实例的 nVars

一般情况下,下边界都是-Inf,上边界都是Inf。因此,我想将 boundaries 属性 lowerupper 的值分别默认为 -Inf * ones([1 nVars])Inf * ones([1 nVars])。现在,我的问题是:如何使 class 属性 的默认值依赖于变量(在本例中为 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

或者,我尝试通过以下方式默认设置边界 class 的属性:

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

任何人都可以帮助我了解如何根据变量分配这些默认值吗?

classdef phase < handle
    properties 
        nVars       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
        upper   double ;
        lower   double ;
    end
    methods
        function obj = boundaries( parent )
            % Assign the parent handle
            obj.parent = parent ;
            % Initialise default values for the properties
            obj.upper =  Inf * ones([1 parent.nVars]);
            obj.lower = -obj.upper ;
        end
    end
end

正确初始化:

>> a = phase(5)
a = 
  phase with properties:

         nVars: 5
    boundaries: [1x1 boundaries]
>> a.boundaries
ans = 
  boundaries with properties:

    parent: [1x1 phase]
     upper: [Inf Inf Inf Inf Inf]
     lower: [-Inf -Inf -Inf -Inf -Inf]

classdef 允许在属性中定义默认值的语法非常方便,以限制必须在构造函数中完成的编码工作(自动检查输入类型和各种输入检查)。

但是,对于您在 属性 块中定义的每个默认值,MATLAB 都会将自动生成的代码添加到对象的构造函数中。最终创建并初始化对象后,如果直接在 属性 块或构造函数中分配 属性 值, 没有区别

对于您的情况,添加到构造函数中的代码非常简单,因此不值得浪费时间来寻找适用于 属性 块的语法。此外,由于另一个问题,这在您的情况下总是会失败:通过引用传递。

当您尝试为 boundaries class 中的父对象分配句柄时,您只是发送了 初始阶段对象的副本 .此副本将位于 boundaries 对象中,但与实际的 phase 父对象分离。为了能够通过引用传递父对象,你需要一个 handle 到这个父对象,为此你需要将父对象 class 定义为 handle.