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 commentaire

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

Connectez-vous pour commenter.

Réponses (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 commentaires

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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Argument Definitions dans Centre d'aide et File Exchange

Question posée :

le 4 Oct 2014

Commenté :

le 6 Oct 2014

Community Treasure Hunt

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

Start Hunting!

Translated by