MATLAB中如何禁止修改初始化结构体的字段?

How to prohibit modifying the field of the initialized structure in MATLAB?

当我用MATLAB写一些复杂的代码时,我想在初始化后禁止修改结构体的字段。

比如我初始化了下面的struct

s = struct('vec', zeros(3, 1), 'val', 1.0)

在下面的过程中,我允许修改字段的值:

s.vec(1) = 1;
s.val    = 2;

我想禁止修改现有字段的大小并禁止向结构添加新字段。 如果我运行下面的代码,我要它return错误信息。

s.vec    = zeros(4, 1);
s.mat    = zeros(3, 3);

如何实现以上功能? 谢谢!

需要自己写class,struct没有这个功能

下面是一个例子,阅读评论了解更多信息。

特别是我正在使用您示例的两个属性创建一个 class,并使用 validateattributes 和 setter 函数添加输入验证。 validateattributes 函数无需您编写即可发出描述性错误。

将以下 class 保存在您的路径中,然后您可以 运行

s = myObject('vec', zeros(3, 1), 'val', 1.0);

如果未作为输入提供,vecval 均默认为 NaN(正确大小)。然后你可以像结构一样索引来设置值,例如

s.vec(1) = 1; % Allowed, s.vec = [1 0 0] now
s.val = 2;    % Allowed
s.vec = zeros(4,1); % Error: Expected input to be of size 3x1, but it is of size 4x1. 
s.mat    = zeros(3, 3); % Error: Unrecognized property 'mat' for class 'myObject'. 

完整 class 示例:

classdef myObject < matlab.mixin.SetGet
    % We have to inherit from the SetGet superclass (could use a "handle"
    % too) to get the setter functions 
    properties
        % Object properties here which can be accessed using dot syntax
        vec
        val
    end
    methods
        function obj = myObject( varargin )            
            % Constructor: called when creating the object
            % Optional inputs for the properties to use name-value pairs
            % similar to struct construction, with default values
            p = inputParser;
            p.addOptional( 'vec', NaN(3,1) );
            p.addOptional( 'val', NaN(1,1) );
            p.parse( varargin{:} );
            % Assign values from inputs (or defaults)
            obj.vec = p.Results.vec;
            obj.val = p.Results.val;
        end
        % Use set functions. These are called when you try to update the
        % corresponding property but allow for input validation before it
        % is stored in the property. 
        function set.vec( obj, v )
            validateattributes( v, {'numeric'}, {'size', [3,1]} );
            obj.vec = v;
        end
        function set.val( obj, v )
            validateattributes( v, {'numeric'}, {'size', [1,1]} );
            obj.val = v;
        end
    end
end