Preventing too many function inputs

9 Ansichten (letzte 30 Tage)
Samuel Brewton
Samuel Brewton am 22 Feb. 2021
Bearbeitet: Stephen23 am 22 Feb. 2021
I am looking for a way to prevent a user from putting in too many inputs for a function. Here is a quick code example:
exfunction(1,3,9)
function exfunction(x,y,z)
switch nargin %Checking # arguements
case 3 %3 function arguements
a=x+y; %Adds x and y
b=x*z; %Multiplies x and z
disp([a,b]); %Displays a and b
otherwise %Less than 3 function arguements (Doesn't work for more than 3)
disp('Wrong Number of Arguements')
end %End switch
end %End function
This function has 3 inputs: x, y, and z. If the user were to only define x and y, it would display "Wrong Number of Arguements" without issue. However, if the user added 4, 5, or any number over the 3 variables, MatLab tries to define the variable (which doesn't exist) and gives me an error.
Any help is appreciated, thanks!

Antworten (1)

per isakson
per isakson am 22 Feb. 2021
Bearbeitet: per isakson am 22 Feb. 2021
>> exfunction(1,3,9,4,5)
throws the error
Error using exfunction
Too many input arguments.
I assume that's the error you encounter and that you want it to handle the situation more gracefully.
Replace
function exfunction(x,y,z)
by
function exfunction( varargin )
if nargin >= 3
disp( 'Too many input arguments. Three anticipated' )
return
else
x = varargin{1};
y = varargin{2};
z = varargin{3};
end
Now
>> exfunction(1,3,9,4,5)
will display
Too many input arguments. Three anticipated
  3 Kommentare
per isakson
per isakson am 22 Feb. 2021
I guess you discovered my error
nargin >= 3
should be
nargin >= 4
Stephen23
Stephen23 am 22 Feb. 2021
Bearbeitet: Stephen23 am 22 Feb. 2021
Note:
  • using varargin means you will not get useful, meaningful information via tab completion or function hinting.
  • Throwing an error is the standard, easy way to handle this. If incorrrect inputs are provided, why let the code continue? This indicates a syntax problem that need to be fixed, not ignored.
Is there a particular reason why throwing an error does not work for you?

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Argument Definitions finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by