Ilya
Ilya

Reputation: 53

Weird behavior of substitution in Mathematica

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]

Upvotes: 5

Views: 1399

Answers (3)

gdelfino
gdelfino

Reputation: 11181

This one is even shorter:

Plot[#[t], {t, 0, 2*Pi}] & /@ {Sin, Cos}

Upvotes: 8

rcollyer
rcollyer

Reputation: 10695

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.

Upvotes: 8

Peter Milley
Peter Milley

Reputation: 2808

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.

Upvotes: 5

Related Questions