Checking the range of input arguments

조회 수: 24 (최근 30일)
Sordin
Sordin 2019년 4월 14일
댓글: Guillaume 2019년 4월 14일
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.

채택된 답변

Guillaume
Guillaume 2019년 4월 14일
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.

추가 답변 (1개)

Sajeer Modavan
Sajeer Modavan 2019년 4월 14일
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
Guillaume
Guillaume 2019년 4월 14일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

제품


릴리스

R2012b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by