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

2 views (last 30 days)
for example :
function y = square(x)
y = x.*x;
end
t1=5;
sq = @(t)square(t);
sq1 = sq(t1);
sq2 = square(t1);

Accepted Answer

Steven Lord
Steven Lord on 3 Jul 2015
Edited: Steven Lord on 6 Jul 2015
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 Comments
Steven Lord
Steven Lord on 6 Jul 2015
Yes, I forgot to add the 2* in the definition of fun2. I've edited the example to correct that mistake.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!