當我用 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);
如何實作以上功能?謝謝!
uj5u.com熱心網友回復:
你需要撰寫自己的類,struct沒有這個功能。
下面是一個示例,請閱讀評論以獲取更多資訊。
特別是,我正在使用您的示例的兩個屬性創建一個類,并使用validateattributes和 setter 函式添加輸入驗證。該validateattributes函式會發出描述性錯誤,而無需您撰寫它們。
將以下類保存在您的路徑上,然后您可以運行
s = myObject('vec', zeros(3, 1), 'val', 1.0);
如果未作為輸入給出,則wherevec和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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/440850.html
