solve second order differential equation in matlab

Solving Second Order Differential Equations with ode45 in MATLAB

Matlab provides the built-in function ode45 to solve ordinary differential equations numerically. In order to use ode45 to solve second order differential equations, we need to create a system of two first order differential equations from the second order one.

Let's consider the second order differential equation:

main.m
y'' + p(t)y' + q(t)y = f(t)
28 chars
2 lines

We can rewrite this as a system of two first order differential equations by introducing a new function z such that:

main.m
y' = z
z' = f(t) - p(t)z - q(t)y
33 chars
3 lines

Now we can use ode45 to solve this system of differential equations numerically.

main.m
% Define p(t), q(t), and f(t)
p = @(t) 1./t;
q = @(t) (2*t-1)./(t.^2);
f = @(t) 10.*exp(-t);

% Define the system of first order differential equations
dydt = @(t, y) [y(2); f(t) - p(t)*y(2) - q(t)*y(1)];

% Define the initial conditions
y0 = [1, 0]; % y(0) = 1, y'(0) = 0

% Define the time interval
tspan = [0, 10];

% Solve the system of differential equations numerically using ode45
[t, y] = ode45(dydt, tspan, y0);

% Plot the solution
plot(t, y(:, 1))
title('Solution of y'''' + y''/t + (2t-1)/t^2 y = 10e^{-t}')
xlabel('t')
ylabel('y')
544 chars
23 lines

This code solves the second order differential equation y'' + y'/t + (2t-1)/t^2 y = 10e^{-t} using ode45 and plots the solution.

gistlibby LogSnag