Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Possible Duplicate:
General::ivar is not a valid variable when plotting - what actually causes this and how to avoid it?

Beginner question:

Why can't I use D[] like that?

Plot[{Sin[x], D[Sin[x], x]}, {x, -2 Pi, 2 Pi}]

If I assign the result of D[] to a variable and put that variable in the list it works.

share|improve this question
1  
What about Plot[{Sin[x], Sin'[x]}, {x, -2 Pi, 2 Pi}]? For any function of type f[x] you can use f'[x] in place of the D[f[x],x]. –  PlatoManiac Apr 5 '12 at 13:22
add comment

marked as duplicate by Anna Lear Oct 27 '12 at 3:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers

up vote 8 down vote accepted

Plot has attribute HoldAll which means in this case that D[Sin[x], x] isn't evaluated until after x is replaced with some number, so you end up with something like D[Sin[-6.28], -6.28] etc. which causes the errors since you can't take a derivative with respect to a number.

One way to get around this is to use Evaluate to evaluate the derivative before the numbers are plugged in, i.e. to do something like

Plot[Evaluate[{Sin[x], D[Sin[x], x]}], {x, -2 Pi, 2 Pi}]

Mathematica graphics

share|improve this answer
    
I find it weird however why Plot[{Sin[x], Evaluate[D[Sin[x], x]]}, {x, -2 Pi, 2 Pi}] won't work. You should be able to evaluate just the D[..] part, shouldn't you? –  0sh Apr 5 '12 at 13:38
4  
@Milosz This is because Evaluate only works on the first level of the held expression. So for example Hold[Evaluate[f[1+2]]] works, but Hold[f[Evaluate[1+2]]] doesn't. –  Heike Apr 5 '12 at 13:49
add comment

Quick answer: The help page for plot states that "Plot has attribute HoldAll, and evaluates f only after assigning specific numerical values to x." Therefore what D[] effectively sees is something like D[Sin[0.1],0.1] (where I chose 0.1 as an arbitrary numerical value) and issues an error message that 0.1 is no valid variable. To work around that you can use Evaluate[] like this

Plot[Evaluate@{Sin[x],D[Sin[x], x]}, {x, -2 Pi, 2 Pi}]
share|improve this answer
add comment

You needn't use Evaluate, consider using of Derivative instead of D if you don't like to use Evaluate. Derivative operates on built-in or user-defined functions and returns pure functions, e.g.

Derivative[#][Sin] & /@ Range[4]
{Cos[#1] &, -Sin[#1] &, -Cos[#1] &, Sin[#1] &}

There are shortcuts for Derivative, e.g. f' or f'' are equivalent respectively to Derivative[1][f] and Derivative[2][f] and in your specific examples it works like this :

Plot[{Sin[x], Derivative[1][Sin][x]}, {x, -2 Pi, 2 Pi}]

enter image description here

share|improve this answer
add comment

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