MATLAB中验证输入的最佳实践

4
在MATLAB函数中验证输入时,何时使用inputParser比assert更好?或者是否还有其他更好的工具可用?
1个回答

5

我个人觉得使用inputParser过于复杂。对于Matlab,始终有三个要检查的事项——存在性、类型和范围/值。有时候你必须分配默认值。以下是一些示例代码,非常典型的错误检查:参数dayofWeek是函数中的第3个参数。(添加了额外的注释。)大部分代码都是在Matlab不存在assert()之前编写的。在我的后期代码中,我使用断言代替if ... error()构造。

%Presence
if nargin < 3 || isempty(dayOfWeek);
    dayOfWeek = '';
end

%Type
if ~ischar(dayOfWeek);
    error(MsgId.ARGUMENT_E, 'dayOfWeek must be a char array.');
end

%Range
days = { 'Fri' 'Sat' 'Sun' 'Mon' 'Tue' 'Wed' 'Thu' };

%A utility function I wrote that checks the value against the first arg, 
%and in this case, assigns the first element if argument is empty, or bad.
dayOfWeek = StringUtil.checkEnum(days, dayOfWeek, 'assign');

%if I'm this far, I know I have a good, valid value for dayOfWeek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接