MATLAB: How do you solve a nonlinear ODE with Matlab using the finite difference approach

differential equationsfinite differencenonlinearnonlinear odeode

I have done this with a linear ODE which had the equation x''+(c/m)*x'+(g/L)*x = 0 where x(0) = pi/6 and x'(0) = 0
%Method 2: Numerical Solution Using the Finite Difference Approach
clear all,close all
m = 1; %Mass of Pendulum (kg)
c = 2; %Friction Coefficient (kg/s)
L = 1; %Length of Pendulum Arm (m)
g = 10; %Gravitational Acceleration (m/s^2)
Nt = 101; %Step Size of time
ti = 0; %Initial time (sec)
tf = 10; %Final time (sec)
t = linspace(ti,tf,Nt); %Time vector (sec)
x1 = pi/6; %Initial Position (radians)
v1 = 0; %Initial Velocity (radians/s)
N = Nt-1; dt = (tf-ti)/N; %dt is the change of t over N which is the step size
%Evaluated Equation Coefficients with Starting Points
% xn is the Angular Position (degrees) of Case 1, Method 2
a = 1 + c*dt/(2*m);
b = 2 - g*dt*dt/L;
d = c*dt/(2*m) - 1;
xn = zeros(1,Nt); xn(1) = x1; xn(2) = xn(1) + v1*dt;
%Loop Over Remaining Discrete Time Points
for i = 2:N
xn(i+1) = b*xn(i)/a + d*xn(i-1)/a;
end
figure(1)
plot(t,xn*180/pi),grid on
title('Linear Model Behavior for Case 1')
xlabel('Time (sec)'), ylabel('Angular Position (degrees)')
This file represents a solution using a finite difference approach for a linear ODE. I would like to do the same with a nonlinear ODE specifically x''+(c/m)*x'+(g/L)*sin(x) = 0 where x(0) = pi/6 and x'(0) = 0. (THE DIFFERENCE IS THE USE OF THE SIN FUNCTION). How can this be done?

Best Answer

All you have to do is replace
b = 2 - g*dt*dt/L;
by
b=2;
and write the new recurrence as
xn(i+1) = b*xn(i)/a + d*xn(i-1)/a - g/L*sin(xn(i))/a.
Best wishes
Torsten.