Preventing too many function inputs

9 ビュー (過去 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 Center および File ExchangeArgument Definitions についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by