Reputation: 147
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?
Upvotes: 5
Views: 1088
Reputation: 3313
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
Upvotes: 6