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

1 vue (au cours des 30 derniers jours)
for example :
function y = square(x)
y = x.*x;
end
t1=5;
sq = @(t)square(t);
sq1 = sq(t1);
sq2 = square(t1);

Réponse acceptée

Steven Lord
Steven Lord le 3 Juil 2015
Modifié(e) : Steven Lord le 6 Juil 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 commentaires
Stephen23
Stephen23 le 4 Juil 2015
Shouldn't fun2 be defined as
y = 2*f(x);
Steven Lord
Steven Lord le 6 Juil 2015
Yes, I forgot to add the 2* in the definition of fun2. I've edited the example to correct that mistake.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by