% Example 12.10 nonlinear equation
% 4th Order Runge-Kutta Method

clear all
close all
clc

% Set the initial parameters
x0 = -5;
h =0.3;
t = [0:h:5];

% Define the ODE of the form dx/dt = f(x,t)
f = @(x,t) t.*x.^2+2.*x;

% Solve ODE using the 4th order Runge-Kutta method
[tout,xout] = rk4(f,t,x0);

% Exact result
xexact = @(t) -20.*exp(2.*t)./(9 - 5.*exp(2.*t) + 10.*exp(2.*t).*t);

% Plot Result
figure
hold on
fplot(xexact,[min(t),max(t)],'LineWidth',2)
plot(tout,xout,'ok','MarkerFaceColor',[0,0,0],'MarkerSize',3)
ylim([-7,0])
xlabel('t')
ylabel('x')
title('Example 12.10')
legend('Exact',['Euler with h = ',num2str(t(2)-t(1)),],'Location','southeast')

% Display the result as a table
fprintf('\n        t       xi\n')
disp('---------------------------')
disp([tout,xout])




% Define the ODE of the form dx/dt = f(t,x)
f2 = @(t,x) t.*x.^2+2.*x;

% Solve ODE using ode45
[tout2,xout2] = ode45(f2,t,x0);

% Plot Result
figure
hold on
plot(tout,xout,'o','MarkerFaceColor',[0, 0.4470, 0.7410],'MarkerSize',5)
plot(tout2,xout2,'o','MarkerFaceColor',[0.8500, 0.3250, 0.0980],'MarkerSize',5)
fplot(xexact,[min(t),max(t)],'--k')
ylim([-7,0])
xlabel('t')
ylabel('x')
title('Example 12.10')
legend(['RK4 with h = ',num2str(t(2)-t(1))],['ode45 with h = ',num2str(t(2)-t(1))],'Exact','Location','southeast')

% Display the result as a table
fprintf('\n        RK4       ode45\n')
disp('---------------------------')
disp([xout,xout2])