在MATLAB中验证输入时的最佳实践

The*_*guy 4 validation matlab

在MATLAB函数中验证输入时,何时使用inputParser比断言更好.或者还有其他更好的工具吗?

Mar*_*arc 5

我个人发现使用inputParser不必要的复杂.对于Matlab,总有3件事要检查 - 存在,类型和范围/值.有时您必须指定默认值.下面是一些示例代码,非常典型的我的错误检查: dayofWeek是函数中的参数,第3个.(添加了额外的评论.)这些代码大部分早assert()于Matlab 的存在.我在后面的代码中使用asserts而不是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
Run Code Online (Sandbox Code Playgroud)