'Not enough input arguments' error with arrayfun
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Antworten (1)
Stephen23
am 22 Okt. 2017
Bearbeitet: Stephen23
am 14 Sep. 2022
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 Kommentare
Jose Daniel Ortiz
am 5 Sep. 2018
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
am 14 Sep. 2022
Bearbeitet: Stephen23
am 14 Sep. 2022
"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.
Siehe auch
Kategorien
Mehr zu Environment and Settings finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!