why anonymous function is needed ?
3 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!