2011-09-22 22 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