How to Draw a Slope Field in MATLAB

Mehak Mubarik Feb 02, 2024
  1. Use the slope_field() Function to Draw a Slope Field of First-Order Ordinary Differential Equations in MATLAB
  2. Use quiver() Function to Draw a Slope Field of First-Order Ordinary Differential Equations in MATLAB
How to Draw a Slope Field in MATLAB

An equality equation that contains function and the derivative of that respective function makes an (ODE) ordinary differential equation.

We use the slope field to clarify our concepts of differential equations. We also call the slope field a directional field.

Use the slope_field() Function to Draw a Slope Field of First-Order Ordinary Differential Equations in MATLAB

The slope_field() function contains three parameters. The first parameter is the f function the equation with x and y parameters we are dealing with.

The second parameter is the minimum and maximum limits in which our x parameter lies. The third parameter is the minimum and maximum limits in which our y parameter lies.

The limits are commonly known as the x and y domains. The function slope_field() helps us plot the slope field of our equation while returning the figure-handle of our field.

Assume, our differential equation is:

$$ \frac {dy} {dx} = \frac {3y} {1-2x} $$

We set the domain of x to be [-1,12] and y to be [-4, 5].

This means our function is f(x,y) = 3y/(1-2x).

f = @(x,y) 3*y/(1-2*x);
figure;
slope_field(f,[-1,12],[-4,5]);
xlabel('$x$','interpreter','latex','fontsize',17);
ylabel('$y$','interpreter','latex','fontsize',17);
title('Slope Field for $\displaystyle\frac{dy}{dx}=\frac{3y}{1-2x}$',...
    'interpreter','latex','fontsize',17);

Output:

Slope Field Function figure 1

In this example, we used the slope_field() function with default settings and visualized the slope field of our desired differential equation.

Use quiver() Function to Draw a Slope Field of First-Order Ordinary Differential Equations in MATLAB

The function quiver() contains four arguments:

  • X-coordinates
  • Y-coordinates
  • Directional component of X-coordinate represented by U.
  • Directional component of Y-coordinate represented by V.

The function returns a graphical representation of the slope field as arrows with coordinates X and Y and directional components U and V.

Assume, our differential equations are:

$$ \frac {dx} {dt} = x^5+6xy-3y $$
$$ \frac {dy} {dt} = -8x+sin\left(2yx\right) $$
[x,y] = meshgrid(-3:0.1:3);
dx = x.^5+6*x.*y-3*y;
dy = -8*x+sin(2*x.*y);
r = ( dx.^2 + dy.^2 ).^0.5;
px = dx./r;
py = dy./r;
quiver(x,y,px,py);

Output:

Quiver Function figure 2

Mehak Mubarik avatar Mehak Mubarik avatar

Mehak is an electrical engineer, a technical content writer, a team collaborator and a digital marketing enthusiast. She loves sketching and playing table tennis. Nature is what attracts her the most.

LinkedIn