%%
%------------------------------------------
% Ex. 9.0.6
clear all
close all

f=@(x,t)(1-x);
xex=@(t,x0)(1+(x0-1)*exp(-t));

t_in=0; t_fin=8; N=50;

hold on

x0=0;
[xRK, t, dt]=RK_1ODE(t_in, t_fin, N, x0, f)
plot(t,xex(t,x0),'r','Linewidth',2)
plot(t,xRK,'xr')

x0=1;
[xRK, t, dt]=RK_1ODE(t_in, t_fin, N, x0, f)
plot(t,xex(t,x0),'b','Linewidth',2)
plot(t,xRK,'xb')

x0=2;
[xRK, t, dt]=RK_1ODE(t_in, t_fin, N, x0, f)
plot(t,xex(t,x0),'g','Linewidth',2)
plot(t,xRK,'xg')

xlabel('t','FontSize',18)
ylabel('x(t)','FontSize',18)
hold off


%%
%------------------------------------------
% Ex. 10.0.8
% Example of logistic equation
clear all
close all
clc

f=@(x,t)(x.*(1-x));

xex=@(t,x0)(x0./(x0+(1-x0)*exp(-t)));

t_in=0; t_fin=5; N=100;

hold on
x0=2;
[xRK, t, dt]=RK_1ODE(t_in, t_fin, N, x0, f)
plot(t,xex(t,x0),'r','Linewidth',1)
plot(t,xRK,'rx')

x0=0.1;
[xRK, t, dt]=RK_1ODE(t_in, t_fin, N, x0, f)
plot(t,xex(t,x0),'b','Linewidth',1)
plot(t,xRK,'bx')

x0=1;
[xRK, t, dt]=RK_1ODE(t_in, t_fin, N, x0, f)
plot(t,xex(t,x0),'g','Linewidth',1)
plot(t,xRK,'gx')

axis([0 4 -1 2])
x0=-0.1;
[xRK, t, dt]=RK_1ODE(t_in, t_fin, N, x0, f)
%plot(t,xex(t,x0),'c','Linewidth',2)
plot(t,xRK,'cx')
xlabel('t','FontSize',18)
ylabel('x(t)','FontSize',18)
hold off

%%
% exercise 9.0.7
clear all
close all
f=@(x)(log(x)+x.^(1/3)-0.2*x.^2);

x=linspace(0.1,5,100)

x2=fzero(f,4);
x1=fzero(f,0.5);

figure(1)
subplot(2,1,1)
hold on
plot(x,f(x))
plot(x,0*ones(100,1),'k--')
plot(x1,f(x1),'sk')
plot(x2,f(x2),'sk')
hold off



f=@(x,t)(log(x)+x.^(1/3)-0.2*x.^2)
t_in=0; t_fin=5; N=100;

subplot(2,1,2)
hold on

x0=0.5;
[xRK, t, dt]=RK_1ODE(t_in, t_fin, N, x0, f)
plot(t,xRK,'r')
plot(t,x2*ones(length(t),1),'k--')

x0=5;
[xRK, t, dt]=RK_1ODE(t_in, t_fin, N, x0, f)
plot(t,xRK,'b')

x0=3;
[xRK, t, dt]=RK_1ODE(t_in, t_fin, N, x0, f)
plot(t,xRK,'g')
hold off

