Question

My question is: why doesn't the following work, and how do I fix it?

Plot[f[t], {t, 0, 2*Pi}] /. {{f -> Sin}, {f -> Cos}}

The result is two blank graphs. By comparison,

DummyFunction[f[t], {t, 0, 2*Pi}] /. {{f -> Sin}, {f -> Cos}}

gives

{DummyFunction[Sin[t], {t, 0, 2 *Pi}],  DummyFunction[Cos[t], {t, 0, 2 * Pi}]}

as desired.

This is a simplified version of what I was actually doing. I was very annoyed that, even after figuring out the annoying "right way" of putting the curly brackets nothing works.

In the end, I did the following, which works:

p[f_] := Plot[f[t], {t, 0, 2*Pi}]
p[Sin]
p[Cos]
Was it helpful?

Solution

Mathematica is trying to evaluate Plot before the substitution. You can prevent that with the Hold and ReleaseHold functions:

ReleaseHold[Hold[Plot[f[t],{t,0,2*Pi}]] /. {{f -> Sin},{f -> Cos}}]

Hold[] will force the entire Plot subexpression to remain unsimplified while the substitution is performed, then ReleaseHold[] will let it proceed with the actual plotting.

OTHER TIPS

As an alternative to Peter's Hold/ReleaseHold strategy you could do

Plot[Evaluate[ f[t]/. {{f -> Sin}, {f -> Cos}} ], {t, 0, 2*Pi}]

which is a little cleaner to read. This ensures that f is substituted before Plot is evaluated.

This one is even shorter:

Plot[#[t], {t, 0, 2*Pi}] & /@ {Sin, Cos}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top