'Not enough input arguments' error with arrayfun

8 次查看(过去 30 天)
Hi All - I am new to MATLAB. I have the following function definition:
function output = y(x)
output = exp(x)/(2 +(x^3));
end
I am trying to pass an array through a function elementwise and generate an output array in which every item is simply the value the function for the respective input item. I have this code;
% define range to plot across
xmax = 5;
xmin = -5;
step = 0.1;
X = xmin:step:xmax;
% pass input range in and collect output
Y = arrayfun(y, X);
% plot output
plot(X,Y)
I am getting the following error;
Not enough input arguments.
Error in y (line 2)
output = exp(x)/(2 +(x^3));
Error in working (line 9)
Y = arrayfun(y, X);
Is anybody able to suggest where I am going wrong? Appreciate the help.

回答(1 个)

Stephen23
Stephen23 2017-10-22
编辑:Stephen23 2022-9-14
The arrayfun documentation states that its first input argument must be a function handle:
For example, you can use @ to create the function handle:
Y = arrayfun(@y, X);
This is required because when you simply write y it calls the function (i.e. evaluates it), just like it would if you typed y in the command window and pushed enter. By using @ you define a function handle, which is passed to arrayfun where it is called internally to evaluate the required values.
  2 个评论
Jose Daniel Ortiz
As someone coming from Python, it is totally unexpected that arrayfun and Matlab behaves in this way. In many languages, functions can be passed without such syntax, for what its worth.
Stephen23
Stephen23 2022-9-14
编辑:Stephen23 2022-9-14
"As someone coming from Python, it is totally unexpected that arrayfun and Matlab behaves in this way. In many languages, functions can be passed without such syntax, for what its worth."
The difference is very simple, it all depends on how functions are called:
  • Python functions must be called using parentheses, so a function without parentheses can be simply interpreted as the function itself (whatever that means) and passed as a variable, etc.
  • in contrast MATLAB permits functions to be called without parentheses... therefore any time you simply write a function name, MATLAB does exactly what you are telling it to do: it calls the function. So if you instead want to pass a function as a variable, something else must be done to distinguish it from simply calling it (without parentheses). That is what function handles are for.
MATLAB was already twenty years old when Python was first released in 1991, and its venerable age is reflected in design decisions that reflect common or desirable programming paradigms of the 1970's.
Complaints when it changes, and complaints when it stays the same.... you can't please everyone.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by