How do I solve a first order ODE numerically in MATLAB?

The other day a student came to ask me for help in solving a first order ordinary differential equation using the ode45 routine of MATLAB.  To use ode45, one needs to be familiar with how the inputs are required by MATLAB.

To solve a first-order ODE by ode45 is straightforward.

The ODE given is given as
3*dy/dx+7*y^1.2=5*x^1.1, y(2)=13.
Find the value of y(19).

Program without comments

clc
clear all
dydx=@(x,y) (5*x^1.1-7*y^1.2)/3
[xx,yy]=ode45(dydx,[2,19],13);
n=length(yy);
yend=yy(n)

 

Program with comments

clc
clear all
% Assume that you are given a first-order differential equation
% 3*dy/dx+7*y^1.2=5*x^1.1, y(2)=13.
% Find the value of y(19).
% How would you solve it by using the ode45 MATLAB function?
% SOLUTION
% First you would need to rewrite ODE as dy/dx=f(x,y) form
% dy/dx=(5*x^1.1-7*y^1.2)/3, y(2)=13
% Define a variable of your choice and write what dy/dx is.
% @(x,y) means these are the independent and dependent variables in ODE
dydx=@(x,y) (5*x^1.1-7*y^1.2)/3
% Look at the ode45 help in MATLAB
% Left hand side yy vector is where you want the values stored.
% xx is the vector that will be chosen by MATLAB, not you, at which it will
% provide you the value of yy vector.
% Inputs to ode45 are the following.
% 1) dydx is the ODE in the form of Line 14.
% 2) [2,19] is the span of xx values. You can observe x=2 is where the
% initial condition is given and x=19 is the value at which you are
% seeking the y value at. These two inputs can be variables too.
% 3) Last input is value of the initial condition that is given at x=2.
% This input can be a variable too.
[xx,yy]=ode45(dydx,[2,19],13);
% Since last entry of yy vector would be where the xx span ends, and that
% is where you want to find the value of y
n=length(yy);
yend=yy(n)

________________________________________

This post is brought to you by

Leave a Reply