calculate a second order differential in matlab

To calculate a second order differential equation in matlab, you first need to convert it into a system of first order differential equations. You can define the second derivative as a new variable and then write two first order differential equations that link it with the original function and its first derivative.

Assuming you have a second order differential equation of the form:

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

where p(t), q(t) and f(t) are functions of t, you can define two new variables z(t) = y'(t) and w(t) = y(t), and write the following system of first order differential equations:

main.m
z(t) = y'(t)
z'(t) = y''(t) = -p(t)*z(t) - q(t)*w(t) + f(t)
60 chars
3 lines

Once you have the system of first order differential equations, you can use the ode45 function in matlab to solve it numerically. You will need to define a function handle that evaluates the right-hand side of the system for a given value of t, z(t) and w(t).

Here's an example code that solves the second order differential equation y''(t) + y(t) = 0 with initial conditions y(0) = 0 and y'(0) = 1:

main.m
% Define the function handle that evaluates the system of differential equations
dydt = @(t,y) [y(2); -y(1)];

% Solve the system using ode45
[t,y] = ode45(dydt, [0 10], [0; 1]);

% Plot the solution
plot(t, y(:,1))
xlabel('t')
ylabel('y(t)')
title('Solution of y''''(t) + y(t) = 0')
284 chars
12 lines

This will produce a plot of the solution y(t) as a function of time t.

gistlibby LogSnag