what's the diffirence between @f1 and directly recall the same function , f1

1 次查看(过去 30 天)
for example :
function y = square(x)
y = x.*x;
end
t1=5;
sq = @(t)square(t);
sq1 = sq(t1);
sq2 = square(t1);

采纳的回答

Steven Lord
Steven Lord 2015-7-3
编辑:Steven Lord 2015-7-6
If you wanted to create functions that evaluated either 2*sin(x), 2*cos(x), or 2*tan(x) you could define three functions:
function y = sin2(x)
y = 2*sin(x);
function y = cos2(x)
y = 2*cos(x);
function y = tan2(x)
y = 2*tan(x);
Note that sin2, cos2, and tan2 look very similar. They have the same structure; the only thing that's different is which trig function they call. So why duplicate that code? You could write one function that can accept [something] representing the function you want to evaluate and double the result of evaluating that [something]. That [something] is a function handle.
function y = fun2(f, x)
y = 2*f(x);
To call fun2 and give the same answer as sin2, use the function handle @sin:
y = fun2(@sin, x);
To call fun2 and give the same answer as cos2, use the function handle @cos:
y = fun2(@cos, x);
The functions sin2, cos2, and tan2 make it clear to anyone reading the code exactly what they do. fun2 doesn't have that same clarity. But fun2 is more flexible than sin2, cos2, or tan2. If I want now to compute 2*log(x), I can reuse fun2 instead of writing a function named log2 (which would conflict with a function already in MATLAB.)
  3 个评论
Steven Lord
Steven Lord 2015-7-6
Yes, I forgot to add the 2* in the definition of fun2. I've edited the example to correct that mistake.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by