How to control the number of inputs in a function

3 views (last 30 days)
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 Comment
Chad Greene
Chad Greene on 6 Oct 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')

Sign in to comment.

Answers (1)

Titus Edelhofer
Titus Edelhofer on 4 Oct 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

Categories

Find more on Argument Definitions in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!