function Figure4_5a

% Matlab code for Figure 4.5(a) in book:
% Radek Erban and Jon Chapman, Stochastic Modelling of Reaction-Diffusion
% Processes, Cambridge University Press, 2019

close all;
randn('state',10);

n=250;
finaltime=10;
deltaU=finaltime/n;
theta=0.5;
nt=1001;
deltat=1;
x=zeros(n,nt);

Dmatrix=diag(-2*ones(n,1));
for i=1:n-1
    Dmatrix(i,i+1)=1;
    Dmatrix(i+1,i)=1;
end

diffusionconstant=1;
Dmatrix=Dmatrix/(deltaU*deltaU);

Lmatrix=diag(ones(n,1))-(theta*deltat/(2*diffusionconstant))*Dmatrix;
Rmatrix=diag(ones(n,1))+((1-theta)*deltat/(2*diffusionconstant))*Dmatrix;

for t=1:nt-1
    x(:,t+1)=inv(Lmatrix)*(Rmatrix*x(:,t)+sqrt(2*deltat/deltaU)*randn(n,1));
end

x=x(:,1:200:nt);
linearX=2*ones(n,1)+[1:n]'/200;

time=[0:n+1];

figure(1);
set(gca,'Fontsize',18);
plot([linearX(1); x(:,2)+linearX; linearX(n)],time,'b');
hold on;
plot([linearX(1); x(:,3)+linearX; linearX(n)],time,'m');
plot([linearX(1); x(:,4)+linearX; linearX(n)],time,'c');
plot([linearX(1); x(:,5)+linearX; linearX(n)],time,'r');
plot([linearX(1); x(:,6)+linearX; linearX(n)],time,'g');
ylabel('time','interpreter','latex');
line([0 0],[-15 n+15],'Color','k','Linewidth',4);
axis([-2.5 6.5 -15 n+15]);
plot([linearX(1) linearX(n)],[0 n+1],'o','Color','k','Markersize',6,'Linewidth',8);
set(gca,'XTick',[0]);
set(gca,'YTick',[0 n+1]);
set(gca,'YTickLabel',{'',''});
text(-2.9,0,'$t$','Fontsize',18,'interpreter','latex');
text(-4.0,n+1,'$t+\Delta{}t$','Fontsize',18,'interpreter','latex');
text(linearX(1)+0.3,0,'$X(t)$','Fontsize',18,'interpreter','latex');
text(linearX(n)+0.3,n,'$X(t+\Delta{}t)$','Fontsize',18,'interpreter','latex');
text(6,-28,'$x$','Fontsize',18,'interpreter','latex');
set(gca,'Fontsize',18);
