% MATLAB file used in the solution of Example 36.2 of "A First Course on
% Kinetics and Reaction Engineering."
function Example_36_2
    % Known constants
    V = 50.; % cm^3
    Vdot = 100.; % cm^3/min
    CAfeed = 1.3/1000; % mol/cm^3
    k = 0.7; % /min
    
    % Given age data
    lambda = [0; 0.1; 0.2; 0.3; 0.4; 0.5; 0.6; 0.7; 0.8; 0.9; 1; 1.1; 
        1.2; 1.3; 1.4; 1.5; 1.6; 1.7; 1.8; 1.9; 2];
    Fprime = [0.00; 0.03; 0.13; 0.21; 0.32; 0.38; 0.46; 0.54; 0.61; 0.68; 
        0.77; 0.80; 0.81; 0.84; 0.85; 0.89; 0.90; 0.91; 0.91; 0.92; 0.93];
    
    % Approximate dFprime/dt, equation (7)
    dFprime_dt = diff(Fprime)./diff(lambda);
    % Set dFprime/dt equal to zero for the last residence time
    dFprime_dt = [
        dFprime_dt
        0
    ];

    % Calculate the normalization factor using the integral in equation (8)
    norm = trapz(lambda,dFprime_dt)
    dFdt = dFprime_dt/norm;
    % Calculate the re-normalized age distribution function using the 
    % integral in equation (8)
    check = trapz(lambda,dFdt)
    
    % Use the late-mixing segregated flow model, equation (10), to
    % calculate the conversion
    integrand = zeros(length(lambda),1);
    for i=1:length(lambda)
        integrand(i) = (1-exp(-k*lambda(i))).*dFdt(i);
    end
    fA = trapz(lambda,integrand)
    
end % of Example_36_2.m

