4.1 Generate direction field plot of a first order differential equation
Problem: Given the following non autonomous differential equation, plot the line fields
which represents the solutions of the ODE.
\[ \frac {dy\left ( x\right ) }{dx}=x^2 - y \]
Direction field plot (or slope plot) shows solutions for the ODE without actually solving
the ODE.
The following are the steps to generate direction field plot for \(\frac {dy}{dx}=f(x,y)\)
- generate 2 lists of numbers. The \(y\) list and the \(x\) list. These 2 lists are the
coordinates at which a small slop line will be plotted.
- At each of the above coordinates \((y,x)\) evaluate \(f(x,y)\).
- Plot small line starting at the point \((x,y)\) and having slop of \(f(x,y)\). The length of the line
is kept small. Normally it has an arrow at the end of it.
Using Matlab, the points are first generated (the \((x,y)\) coordinates) then the slope \(f(x,y)\) evaluated at
each of these points, then the command quiver() is used. Next contour() command is used
to plot few lines of constant slope.
In Mathematica, the command VectorPlot is used. In Maple dfieldplot is
used.
| Mathematica
f[x_,y_]:= x^2-y
ListVectorPlot[Table[{1,f[x,y]},
{x,-2,2,0.1},{y,-2,2,0.1}],
FrameLabel->{{"y(x)",None},
{"x",
"direction fields for y'(x)=x^2-y"}
},
ImageSize->350,
LabelStyle->Directive[14]]
|
|
StreamPlot[{1,f[x,y]},{x,-2,2},{y,-2,2},
FrameLabel->{{"y(x)",None},
{"x","direction fields for y'(x)=x^2-y"}},
ImageSize->350,
LabelStyle->Directive[14]]
|
|
| Matlab
clear all; close all;
%direction fields for dy/dx=xy
f = @(X,Y) X.^2 - Y;
[X,Y] = meshgrid(-2:.4:2,-2:.4:2);
YlengthOfVector = f(X,Y);
XlengthOfVector = ones(size(YlengthOfVector));
quiver(X,Y,XlengthOfVector,YlengthOfVector);
xlabel('x'); ylabel('y');
hold on;
contour(X,Y,YlengthOfVector,...
[-5 -4 -3 -2 -1 0 1 2 3 4 5]);
title(...
'direction fields for $\frac{dy}{dx}=x^2-y$',...
'interpreter','latex','fontsize',12)
|
|
| Maple
restart;
with(DEtools): with(plots):
ode1:=diff(y(x),x)=(y(x))^2-x;
dfieldplot(ode1,y(x),x=-6..10, y=-4..4,
arrows=MEDIUM,
title=`Line fields for an non-autonomous ODE`);
|
|
restart;
with(DEtools): with(plots):
ode1:=diff(y(x),x)=(y(x))^2-x:
p1:= dfieldplot(ode1,y(x),x=-6..10, y=-6..6,
arrows=MEDIUM):
sol:=dsolve({ode1,y(0)=0});
|
\[ y \left ( x \right ) =-{\frac {\sqrt {3}{{\rm Ai}^{(1)}\left (x\right )}+{{\rm Bi}^{(1)}\left (x\right )}}{\sqrt {3}{{\rm Ai}\left (x\right )}+{{\rm Bi}\left (x\right )}}} \] |
p2:=plot(rhs(sol),x=-6..10,
color=black,thickness=3):
display({p1,p2},
title=`Line fields and solution lines
for an non-autonomous ODE`);
|
|