10

I am trying to plot slope fields of some differential equations using mathematica but can't figure it out. Say I have the equation

    y' = y(t) 
    y(t) = C * E^t

How do I plot the slope field?

I found an example but way to complex for me to understand http://demonstrations.wolfram.com/SlopeFields/

user968102
  • 503
  • 2
  • 6
  • 11

2 Answers2

18

The command you need (since version 7) is VectorPlot. There are good examples in the documentation.

I think the case that you're interested in is a differential equation

y'[x] == f[x, y[x]]

In the case you gave in your question,

f[x_, y_] := y

Which integrates to the exponential

In[]:= sol = DSolve[y'[x] == f[x, y[x]], y, x]
Out[]= {{y -> Function[{x}, E^x c]}}

We can plot the slope field (see wikibooks:ODE:Graphing) using

VectorPlot[{1, f[x, y]}, {x, -2, 2}, {y, -2, 2}]

y

This can be plotted with the solutions to the DE using something like

Show[VectorPlot[{1, f[x, y]}, {x, -2, 2}, {y, -2, 8}, 
   VectorStyle -> Arrowheads[0.03]],
 Plot[Evaluate[Table[y[x] /. sol, {c, -10, 10, 1}]], {x, -2, 2}, 
   PlotRange -> All]]

y again

Maybe a more interesting example is the Gaussian

In[]:= f[x_, y_] := -x y

In[]:= sol = DSolve[y'[x] == f[x, y[x]], y, x] /. C[1] -> c
Out[]= {{y -> Function[{x}, E^(-(x^2/2)) c]}}

Show[VectorPlot[{1, f[x, y]}, {x, -2, 2}, {y, -2, 8}, 
  VectorStyle -> Arrowheads[0.026]],
 Plot[Evaluate[Table[y[x] /. sol, {c, -10, 10, 1}]], {x, -2, 2}, 
  PlotRange -> All]]

-xy


Finally, there is a related concept of the gradient field, where you look at the gradient (vector derivative) of a function:

In[]:= f[x_, y_] := Sin[x y]
       D[f[x, y], {{x, y}}]
       VectorPlot[%, {x, -2, 2}, {y, -2, 2}]

Out[]= {y Cos[x y], x Cos[x y]}

Sin[x y]

Simon
  • 14,631
  • 4
  • 41
  • 101
0

It would appear from the demonstration you linked that it takes a function f(x,y) but you have a set of differentials. However, knowing that f(x,y)=y(x)', you could just use f(x,y)=C*E^x where x=t. My Differentials might be a little rusty, but I'm pretty sure that's right.

J. Lebeuf
  • 43
  • 1
  • 6
  • anyone got a 1 liner for slope fields? – user968102 Jan 18 '12 at 06:27
  • 1 liner? If you need to know how to put it in you can check http://www.physicsforums.com/showthread.php?t=152157 It's a bit more than one line as Mathematica apparently needs a library imported then the call the the plotting function itself is a bit more. – J. Lebeuf Jan 18 '12 at 07:38