Checking the range of input arguments
17 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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.
0 个评论
更多回答(1 个)
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
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 Center 和 File Exchange 中查找有关 Argument Definitions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!