How to control the number of inputs in a function
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Chad Greene
am 6 Okt. 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')
Antworten (1)
Titus Edelhofer
am 4 Okt. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Argument Definitions finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!