Filter löschen
Filter löschen

why anonymous function is needed ?

3 Ansichten (letzte 30 Tage)
Odien
Odien am 9 Aug. 2015
Kommentiert: David Young am 10 Aug. 2015
i am currently confusing with this question,i try to search in matlab but all i get is the way to use the anonymous function =@ .
I try without using the anonymous function and this is what i got,
>> f= x^3 + x^2 + 3*x + 4;
>> Myareaofcurve(f,2,6,100)
Attempted to access f(2); index out of bounds because numel(f)=1.
Error in Myareaofcurve (line 18)
sum_even = ........
with =@
>> f= @(x) x^3 + x^2 + 3*x + 4;
>> Myareaofcurve(f,2,6,100)
Area_using_simpsonsrule =
453.3333
I need to know why.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 9 Aug. 2015
= x^3 + x^2 + 3*x + 4; would require that x already been given a definite value, and it would calculate f as being a particular numeric value. The x would have to be a numeric scalar or a square two-dimensional array for that code to work. For example if x = 3 before that, then f would be assigned the single scalar value 49. You then pass that numeric f into the routine that tries to access the numeric array as a function, and that of course fails.
= @(x) x^3 + x^2 + 3*x + 4; would define a rule, that f is to be a function that expects a single argument that for the purposes of the call will be known as x. For any one call, the x that is passed in to the function is to have the formula applied to it and the result returned. If a different argument is provided then a different result would be calculated.
= @(x) x^3 + x^2 + 3*x + 4; is mostly equivalent to having written
function r = f(x)
r = x^3 + x^2 + 3*x + 4;
end
but does have some subtle differences not worth discussing at the moment.
  5 Kommentare
David Young
David Young am 10 Aug. 2015
Thanks - interesting!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Function Creation 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!

Translated by