% Example LEP-WEB17-1d: Segregation Model with Bimodal distribution
%

tspan = [0 6]; % Range for the independent variable
y0 = [1 0 0 0 0 0 0]; % Initial values for the dependent variables
k1=1;
k2=1;
[t,y]=ode45(@(t,y)ODEfun(t,y,k1,k2),tspan,y0);
tiledlayout(2,2)
set (gcf,'Position',[0,0.1,700,500])
nexttile
plot(t,y(:,4),t,y(:,5),t,y(:,6),'LineWidth',1.5);
xlabel('time (mins)')
ylabel('Concentration')
leg=legend('C_Abar','C_Bbar','C_Cbar','Location','NorthEast');
axis([0 6 0 1])
grid on
leg.ItemTokenSize=[10,10];
title('Concentration profile')
z=size(y);
ca0 =  1;
for i=1:z(1,1)
   X(i)=1-y(i,1)/ca0;  
   ra(i) =  -k1*y(i,1);
   rb(i) =  k1*y(i,1)-k2*y(i,2);
   rc(i) =  k2*y(i,2);
end
nexttile
plot(t,X(1:z(1,1)),t,y(:,7),'LineWidth',1.5)
xlabel('time (mins)')
ylabel('Conversion')
leg=legend('X','Xbar','Location','NorthEast');
leg.ItemTokenSize=[10,10];
title('Conversion profile')
axis([0 6 0 1])
grid on
nexttile
plot(t,-ra(1:z(1,1)),t,-rb(1:z(1,1)),t,-rc(1:z(1,1)),'LineWidth',1.5)
xlabel('time (mins)')
ylabel('Rate')
leg=legend('-r_A','-r_B','-r_C','Location','NorthEast');
leg.ItemTokenSize=[10,10];
title('Rate profile')
axis([0 6 -3 3])
grid on

%

function dYfuncvecdt = ODEfun(t,Yfuncvec,k1,k2); 
ca= Yfuncvec(1);
cb= Yfuncvec(2);
cc= Yfuncvec(3);
cabar= Yfuncvec(4);
cbbar= Yfuncvec(5);
ccbar= Yfuncvec(6);
Xbar=Yfuncvec(7);
% Explicit equations
ca0 =  1;
ra =  -k1*ca;
rb =  k1*ca-k2*cb;
rc =  k2*cb;
X =  1-ca/ca0;
E1 =  0.47219*t^4-1.30733*t^3+0.31723*t^2+0.85688*t+0.20909;
E2 =  3.83999*t^6-58.16185*t^5+366.20970*t^4-1224.66963*t^3+2289.84857*t^2-2265.62125*t+925.46463;
E3 =  0.00410*t^4-0.07593*t^3+0.52276*t^2-1.59457*t+1.84445;
if t<=1.82
    E=E1;
elseif t<=2.8
    E=E2;
else
  E=E3;
end  
% Differential equations
dcadt =  ra;
dcbdt =  rb; 
dccdt =  rc; 
dcabardt =  ca*E;
dcbbardt =  cb*E;
dccbardt =  cc*E;
dXbardt =  X*E;
dYfuncvecdt=[dcadt;dcbdt;dccdt;dcabardt;dcbbardt;dccbardt;dXbardt];
end