필터 지우기
필터 지우기

why anonymous function is needed ?

조회 수: 3 (최근 30일)
Odien
Odien 2015년 8월 9일
댓글: David Young 2015년 8월 10일
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.

채택된 답변

Walter Roberson
Walter Roberson 2015년 8월 9일
= 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
David Young
David Young 2015년 8월 10일
Thanks - interesting!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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