How to control the number of inputs in a function

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

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')

Iniciar sesión para comentar.

Respuestas (1)

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

Marjan
Marjan el 4 de Oct. de 2014
Thanx a lot :)
If that helps, you might mark the question as answered ...
Titus

Iniciar sesión para comentar.

Categorías

Más información sobre Argument Definitions en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 4 de Oct. de 2014

Comentada:

el 6 de Oct. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by