使用验证函数以避免不必要的类和大小转换
当传递给函数的参量值与验证所要求的类和大小不匹配时,MATLAB® 会尽可能将该值转换为声明的类和大小。要在参量验证中避免 MATLAB 执行标准转换,请使用验证函数,而不是类和大小限制。对验证函数的调用不会返回值,也无法更改参量的值。
例如,此函数将第一个输入限制为 double
类的任意大小的二维数组。第二个输入必须为任何类的 5×3 数组。
function f(a,b) arguments a (:,:) double b (5,3) end % Function code end
由于存在标准 MATLAB 类型转换和标量扩展,您可以使用以下输入调用此函数,而不会收到验证错误。
f('character vector',144)
默认情况下,MATLAB 将字符向量的元素转换为其等效数值,并应用标量扩展以基于标量值 144
创建一个 5×3 数组。
使用专用验证函数可以提供更具体的参量验证。例如,此函数定义专用验证函数,用于代替第一个和第二个参量的类和大小设定。这些局部函数帮助您避免输入值转换。
mustBeOfClass
将输入限制为特定类,不允许转换或子类化。要了解相关函数的信息,请参阅mustBeA
。mustBeEqualSize
限制两个输入的大小相等,不允许标量扩展。要了解相关函数的信息,请参阅mustBeScalarOrEmpty
。mustBeDims
将输入限制为具有指定的维度,不允许转置或标量扩展。要了解相关函数的信息,请参阅mustBeVector
。
function fCustomValidators(a,b) arguments a {mustBeOfClass(a,'double'), mustBeDims(a,2)} b {mustBeEqualSize(b,a)} end % Function code end % Custom validator functions function mustBeOfClass(input,className) % Test for specific class name cname = class(input); if ~strcmp(cname,className) eid = 'Class:notCorrectClass'; msg = 'Input must be of class %s.'; error(eid,msg,className); end end function mustBeEqualSize(a,b) % Test for equal size if ~isequal(size(a),size(b)) eid = 'Size:notEqual'; msg = 'Inputs must have equal size.'; error(eid,msg) end end function mustBeDims(input,numDims) % Test for number of dimensions if ~isequal(length(size(input)),numDims) eid = 'Size:wrongDimensions'; msg = ['Input must have ',num2str(numDims),' dimension(s).']; error(eid,msg,numDims) end end
使用 fCustomValidators
测试 mustBeOfClass
函数。第一个参量不属于类 double
,因此该函数返回错误。
fCustomValidators('character vector',144)
Error using fCustomValidators fCustomValidators('character vector',144) ↑ Invalid argument at position 1. Input must be of class double.
在此调用中,第一个输入的维数是错误的,因此验证函数返回自定义错误消息。
fCustomValidators(ones(2,2,4),144)
Error using fCustomValidators fCustomValidators(ones(2,2,4),144) ↑ Invalid argument at position 1. Input must have 2 dimension(s).
mustBeEqualSize
验证器检查输入的大小是否相同。
fCustomValidators(ones(2,2),144)
Error using fCustomValidators fCustomValidators(ones(2,2),144) ↑ Invalid argument at position 2. Inputs must have equal size.
要了解相关预定义验证函数的信息,请参阅 mustBeA
、mustBeFloat
和 mustBeVector
。