Main Content

通过 validateattributes 检查函数输入

使用 validateattributes 函数验证您的函数的输入是否符合一组要求。

validateattributes 要求您传递要检查的变量以及该变量支持的数据类型。或者,传递描述有效维度或值的一组属性。

检查数据类型和其他属性

在名为 checkme.m 的文件中定义最多可接受以下三个输入的函数:abc。检查以下条件:

  • a 是否由双精度正值组成的二维数组。

  • b 是否在一个有 10 列的数组中包含 100 个数值。

  • c 是否为非空字符向量或元胞数组。

function checkme(a,b,c)

validateattributes(a,{'double'},{'positive','2d'})
validateattributes(b,{'numeric'},{'numel',100,'ncols',10})
validateattributes(c,{'char','cell'},{'nonempty'})

disp('All inputs are ok.')

花括号 {} 指示数据类型集和其他属性集都位于元胞数组中。元胞数组允许您将文本与数值数据的组合或不同长度的字符向量存储在单个变量中。

调用带有有效输入的 checkme

checkme(pi,rand(5,10,2),'text')
All inputs are ok.

标量值 pi 是二维值,因为 size(pi) = [1,1]

调用带有无效输入的 checkmevalidateattributes 函数对首个验证失败的输入报错,checkme 停止处理。

checkme(-4)
Error using checkme (line 3)
Expected input to be positive.
checkme(pi,rand(3,4,2))
Error using checkme (line 4)
Expected input to be an array with number of elements equal to 100.
checkme(pi,rand(5,10,2),struct)
Error using checkme (line 5)
Expected input to be one of these types:

  char, cell

Instead its type was struct.

默认错误消息使用通用词 input 来表示验证失败的参量。使用默认错误消息时,确定失败输入的唯一方法是查看 checkme 中的指定代码行。

在错误中添加输入名称和位置

在名称为 checkdetails.m 的文件中定义一个函数,该函数执行与 checkme 相同的验证,但在错误消息中添加有关输入名称和位置的详细信息。

function checkdetails(a,b,c)

validateattributes(a,{'double'},{'positive','2d'},'','First',1)
validateattributes(b,{'numeric'},{'numel',100,'ncols',10},'','Second',2)
validateattributes(c,{'char'},{'nonempty'},'','Third',3)

disp('All inputs are ok.')

validateattributes 的第四个输入的空字符向量 '' 是可选函数名称的占位符。您无需指定函数名称,因为它已显示在错误消息中。当您需要将函数名称包含在错误标识符中以进行更多的错误处理时,请指定函数名称。

调用带有无效输入的 checkdetails

checkdetails(-4)
Error using checkdetails (line 3)
Expected input number 1, First, to be positive.
checkdetails(pi,rand(3,4,2))
Error using checkdetails (line 4)
Expected input number 2, Second, to be an array with
number of elements equal to 100.

另请参阅

|