How to control the number of inputs in a function
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi everybody, I would like to know how I can manage the number of inputs in a function. I have a function with two input parameters and I have to call it by one, two and three input arguments. I have used 'nargin' for this purpose and I managed to control it in case of one input. But when I use nargin for controlling 3 inputs it shows error. My code:
if nargin < 2 disp 'Dear, Not enough input arguments.' return end if nargin ==3 disp 'Dear, Too manyw input arguments.' return end
1 comentario
Chad Greene
el 6 de Oct. de 2014
This is not the question you asked, but you may find it useful: I find assert to be more elegant than if statements and errors. Your
if nargin<2
disp('too many')
return
end
can be rewritten like this:
assert(nargin>=2,'too many')
Respuestas (1)
Titus Edelhofer
el 4 de Oct. de 2014
Hi Marjan,
the problem is that you cannot capture too many input variables inside the function because the error already occured before you can catch it. What you can do is to use varargin for this. One possibility:
function myfun(x, y, varargin)
if nargin>=3
disp('Dear, too many.');
end
Slightly better than that is to use narginchk for this purpose.
Titus
2 comentarios
Titus Edelhofer
el 6 de Oct. de 2014
If that helps, you might mark the question as answered ...
Titus
Ver también
Categorías
Más información sobre Argument Definitions en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!