Preventing too many function inputs

10 vues (au cours des 30 derniers jours)
Samuel Brewton
Samuel Brewton le 22 Fév 2021
Modifié(e) : Stephen23 le 22 Fév 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!

Réponses (1)

per isakson
per isakson le 22 Fév 2021
Modifié(e) : per isakson le 22 Fév 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 commentaires
per isakson
per isakson le 22 Fév 2021
I guess you discovered my error
nargin >= 3
should be
nargin >= 4
Stephen23
Stephen23 le 22 Fév 2021
Modifié(e) : Stephen23 le 22 Fév 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?

Connectez-vous pour commenter.

Catégories

En savoir plus sur Argument Definitions dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by