0
$\begingroup$

Why does

t = 2 Pi;
Plot[D[Sin[x],x], {x,0,t}] (* Plotting the derivative of Sin[x] *)

not work, but

t = 2 Pi;
Plot[Evaluate[D[Sin[x],x], {x,0,t}] (* Plotting the evaluation of the derivative of Sin[x]? *)

do? And why does this work, but neither

t = 2 Pi;
Plot[{D[Sin[x],x]}, {x,0,t}] (* Plotting the one-length array of the derivative of Sin[x] *)

nor

t = 2 Pi;
Plot[{Evaluate[D[Sin[x],x]]}, {x,0,t}] (* Plotting the one-length array of the evaluation of the derivative of Sin[x]? *)

works?

$\endgroup$
3
  • 1
    $\begingroup$ umm, none of these work unless you define t, but to answer the question, it is because one of the attributes of the Plot function is HoldAll. The relevant documentation has an example with Plot that explains in more detail $\endgroup$
    – gpap
    Nov 4, 2013 at 13:17
  • $\begingroup$ I added the constant t. I still don't quite understand, though. In the first example, I have an evaluated function, and Plot needs an evaluated one. In the fourth example I should have the same thing, but inside an array. $\endgroup$ Nov 4, 2013 at 13:57
  • $\begingroup$ In the first example you don't have an evaluated function. That's precisely the point. The derivative is held by Plot and then values for x are filled in. You then have a derivative with respect to a number which is nonsense. $\endgroup$ Nov 4, 2013 at 14:27

1 Answer 1

12
$\begingroup$

I always picture it like this: Plot has attribute HoldAll, so it gets the unevaluated expression D[Sin[x],x]. Then it replaces all occurrences of x with 5 and evaluates the result. So it tries to evaluate something like D[Sin[5],5]. Which is of course nonsensical, because you can't derive by a constant.

If you call Plot[Evaluate[D[Sin[x],x], ..., the expression gets evaluated before it's passed to Plot. So it's equivalent to Plot[Cos[x], {x, 0, t}]. Now if Plot replaces x by 5, it gets a nice real number it can plot.

However, this only happens when Evaluate is the head of the expression passed to Plot. If you pass something like x+5/(Evaluate[y]), the subexpression y isn't evaluated. HoldAll doesn't "look inside" the expression, to see if there's an Evaluate nested somewhere. That's why Plot[{Evaluate[D[Sin[x],x]]}, ... doesn't work.

However, Plot[Evaluate[{D[Sin[x], x]}], {x, 0, t}] does work, because Evaluate is the head of the expression

$\endgroup$
1
  • $\begingroup$ But oddly, the ' format of D works without Evaluate. $\endgroup$ Oct 15, 2022 at 23:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.