Preventing too many function inputs

조회 수: 4 (최근 30일)
Samuel Brewton
Samuel Brewton 2021년 2월 22일
편집: Stephen23 2021년 2월 22일
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!

답변 (1개)

per isakson
per isakson 2021년 2월 22일
편집: per isakson 2021년 2월 22일
>> 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
per isakson
per isakson 2021년 2월 22일
I guess you discovered my error
nargin >= 3
should be
nargin >= 4
Stephen23
Stephen23 2021년 2월 22일
편집: Stephen23 2021년 2월 22일
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?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by