Hi, what should I do to get the 'Not enough input arguments'-error,

9 次查看(过去 30 天)
If I call my own function with not enough input arguments MATLAB realizes this not until the missing variable is used.
Example:
function d = inputErrorCheck(a,b,c)
if a > b
d = a+b;
else
d = a+c;
end;
end
Output:
>> inputErrorCheck(3,2)
ans = 5
>> inputErrorCheck(2,3)
Not enough input arguments.
Error in inputErrorCheck (line 6) d = a+c;
Is there a setting or something to get MATLAB to check the amount of input arguments before it starts the function?
Thanks!

采纳的回答

Clemens Lindscheid
Clemens Lindscheid 2016-11-11
Hi Rebecca,
your problem seems to be closely related to the question of strict data typing for function arguments in Matlab. As far as I know, you cannot do it automatically in Matlab. Matlab functions usually start with checking the number and data type of the input arguments manually, see e.g. gaussmf from the statistics toolbox with 7 lines of checking input arguments and 2 lines of actual code (R2014b).
There are several ways of checking the input arguments:
  • Using nargin (or narginchk), is* and error. Check the Fundamental MATLAB Classes to get a feeling of the checks you need to perform.
  • Using the validateattributes function.
  • Using the inputParser class.
  • Using try catch
  • Compile it as a mex-function. You will need to specify the datatypes before compiling.

更多回答(1 个)

Mischa Kim
Mischa Kim 2016-11-9
Rebecca, yes. Use something like
function d = inputErrorCheck(a,b,vargin)
switch nargin
case 3
if a > b
d = a + b;
else
d = a + vargin;
end
case 2
d = a + b;
end
end
  2 个评论
Rebecca Sippel
Rebecca Sippel 2016-11-10
Hi Mischa, thanks for your answer but this is not exactly what I am searching for. Maybe my question was to vague.
The third variable should not be optional. The function must not be started if there aren't enough input arguments. I don't have the problem with too many arguments because MATLAB checks this.
Example:
>> inputErrorCheck(2,3,4,5)
Error using inputErrorCheck Too many input arguments.
I know that narginchk(a,b) exists but I don't want to use it in every function. I was looking for a kind of setting in MATLAB itself to autocheck if there are not enough variables like it works with too many variables.
Jan
Jan 2016-11-10
@Rebecca: There cannot be a switch in Matlab to restrict the number of inputs, because many built-in functions use optional arguments. It is a typical programming style in Matlab.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by