在MATLAB中验证输入的最佳做法 [英] Best practice when validating input in MATLAB
问题描述
在MATLAB函数中验证输入时,何时使用inputParser比断言更好.还是有其他甚至更好的工具可用?
When is it better to use an inputParser than assert when validating input in a MATLAB function. Or is there other, even better tools available?
推荐答案
我个人发现使用inputParser不必要地复杂.对于Matlab,始终需要检查三件事-状态,类型和范围/值.有时您必须指定默认值.这是一些示例代码,是我进行错误检查时非常典型的示例:dayofWeek
是参数,函数中的第3个. (添加了额外的注释.)大多数此类代码在Matlab中早于assert()
的存在.我在以后的代码中使用断言,而不是if ... error()
构造.
I personally found using the inputParser unnecessarily complicated. For Matlab, there are always 3 things to check - Presence, Type and Range/Values. Sometimes you have to assign defaults. Here is some sample code, very typical of my error checking: dayofWeek
is the argument, 3rd in the function. (Extra comments added.) Most of this code predates the existence of assert()
in Matlab. I use asserts in my later code instead of the if ... error()
constructs.
%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
这篇关于在MATLAB中验证输入的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!