当我用 MATLAB 编写一些复杂的代码时,我想在初始化结构体后禁止修改其字段。
例如,我初始化以下结构
s = struct('vec', zeros(3, 1), 'val', 1.0)
在以下过程中,我允许修改字段的值:
s.vec(1) = 1;
s.val = 2;
我想禁止修改现有字段的大小并禁止向结构添加新字段。 如果我运行以下代码,我希望它返回错误信息。
s.vec = zeros(4, 1);
s.mat = zeros(3, 3);
上述功能如何实现? 谢谢!
最佳答案
需要自己写一个类,struct
没有这个功能。
下面是一个示例,请阅读评论以获取更多信息。
特别是,我正在创建一个具有示例的两个属性的类,并使用 validateattributes
和 setter 函数添加输入验证。 validateattributes
函数会发出描述性错误,而无需您编写它们。
将以下类保存在您的路径上,然后您可以运行
s = myObject('vec', zeros(3, 1), 'val', 1.0);
如果没有作为输入给出,vec
和 val
都默认为 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'.
全类示例:
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
关于matlab - MATLAB中如何禁止修改初始化结构体的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71418322/