当我用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);如何实现上述功能?谢谢!
发布于 2022-03-10 08:56:53
您需要编写自己的类,struct没有此功能。
下面是一个例子,阅读注释获得更多信息。
特别是,我使用示例的两个属性创建了一个类,并使用validateattributes和setter函数添加了输入验证。validateattributes函数无需编写描述性错误就会发出描述性错误。
将下面的类保存在path上,然后可以运行
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
endhttps://stackoverflow.com/questions/71418322
复制相似问题