2011-09-22 26 views

回答

5

我个人发现使用inputParser不必要的复杂。对于Matlab,总有3件事要检查 - 存在,类型和范围/值。有时你必须分配默认值。下面是一些示例代码,非常典型的我的错误检查: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