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
params =[varargin{1:2}];
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)
validateattributes(a, {'numeric'}, {'scalar', 'finite', 'real', '>', 0, '<', 1}, 1, 'myfun');
validateattributes(b, {'numeric'}, {'scalar', 'finite', 'real', '>', 0, '<', 1}, 2, 'myfun');
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.
Best Answer