我个人发现使用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)
| 归档时间: |
|
| 查看次数: |
966 次 |
| 最近记录: |