Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 433
Ilya Avatar asked Dec 03 '22 05:12

Ilya


2 Answers

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.

like image 130
rcollyer Avatar answered Feb 01 '23 12:02

rcollyer


This one is even shorter:

Plot[#[t], {t, 0, 2*Pi}] & /@ {Sin, Cos}
like image 21
gdelfino Avatar answered Feb 01 '23 11:02

gdelfino