Best practice for validating input in MATLAB

When is it better to use an input parser than to state when checking input in MATLAB functions. Or are there other, better tools?

+4
source share
1 answer

I personally found that using inputParser is unnecessarily complicated. For Matlab, there are always three things to check: presence, type, and range / values. Sometimes you have to assign default values. Here is a sample code that is very typical of my error checking: dayofWeek is the argument, the third in the function. (Additional comments added.) Most of this code predates the existence of assert() in Matlab. I use assertions in my later code instead of 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 
+5
source

All Articles