Preventing too many function inputs

9 visualizaciones (últimos 30 días)
Samuel Brewton
Samuel Brewton el 22 de Feb. de 2021
Editada: Stephen23 el 22 de Feb. de 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!

Respuestas (1)

per isakson
per isakson el 22 de Feb. de 2021
Editada: per isakson el 22 de Feb. de 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 comentarios
per isakson
per isakson el 22 de Feb. de 2021
I guess you discovered my error
nargin >= 3
should be
nargin >= 4
Stephen23
Stephen23 el 22 de Feb. de 2021
Editada: Stephen23 el 22 de Feb. de 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?

Iniciar sesión para comentar.

Categorías

Más información sobre Argument Definitions en Help Center y File Exchange.

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by