MATLAB Answers

Checking the range of input arguments

19 views (last 30 days)
Sordin
Sordin on 14 Apr 2019
Commented: Guillaume on 14 Apr 2019
I have a function where two of the input parameters (a and b) must be within the range . So I have written the following code to check if the input arguments are valid:
if ~(varargin{1} > 0 && varargin{1} < 1), error('Parameters must be in the interval [0,1]')
else
a = varargin{1};
end
if ~(varargin{2} > 0 && varargin{2} < 1), error('Parameters must be in the interval [0,1]')
else
b = varargin{2};
end
But I am repeating the same process twice, so I am wondering if there is a more compact way to apply the same criterion to both parameters simultaneously. Is there a shorter way to write this code?
Any suggestions would be greatly appreciated.

  0 Comments

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 14 Apr 2019
Do you actually need to use varargin? It doesn't appear to server any purpose here, if you always assign the same variable.It looks like it just complicates your code unnecessary.
The only difference between the two blocks of code is the assignment to a different variable, so the question is: do these need to be in a different variable? Most likely, the answer is no. You could just keep referring to them as varargin{1} and varargin{2} and stuff them together in the same array (assuming the two variables are the same size and shape). If you do that, you can wrap your test in a loop:
for vidx = 1:2
if ~(varargin{vidx} > 0 && varagin{vidx} < 1)
error('Parameter %d must be in the interval [0,1]', vidx));
end
end
%keep using varargin{1} and varargin{2}, or
params =[varargin{1:2}]; %concatenate into a vector (assuming scalar)
However, personally, I'd use validateattributes and bearing in mind that as I said, varargin is not needed this is what I'd use:
function myfun(a, b, varargin) %if there's some more inputs required as varargin
validateattributes(a, {'numeric'}, {'scalar', 'finite', 'real', '>', 0, '<', 1}, 1, 'myfun');
validateattributes(b, {'numeric'}, {'scalar', 'finite', 'real', '>', 0, '<', 1}, 2, 'myfun');
%... rest of the code
end
With validateattributes you're checking a lot more than just being in the range (0,1), you're also making sure that the numbers are not complex, are the right size, etc.

  0 Comments

Sign in to comment.

More Answers (1)

Mohamed Sajeer Ibn Azad Modavan
if ~(varargin{1,2} > 0 && varargin{1,2} < 1), error('Parameters must be in the interval [0,1]')
else
a = varargin{1};
b = varargin{2};
end

  1 Comment

Guillaume
Guillaume on 14 Apr 2019
varargin is always a row vector. So varargin{1, 2} is always equivalent to varargin{2}.
The above only checks that the 2nd argument is valid.

Sign in to comment.

Sign in to answer this question.

Products


Release

R2012b