Borrar filtros
Borrar filtros

why anonymous function is needed ?

3 visualizaciones (últimos 30 días)
Odien
Odien el 9 de Ag. de 2015
Comentada: David Young el 10 de Ag. de 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.

Respuesta aceptada

Walter Roberson
Walter Roberson el 9 de Ag. de 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 comentarios
David Young
David Young el 10 de Ag. de 2015
Thanks - interesting!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Function Creation en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by