% Modified version of the MATLAB template file SolvNonDif.m used in the
% solution of Example 30.1 of "A First Course on Kinetics and Reaction
% Engineering."
%
function Example_30_1
    % Known quantities and constants (in consistent units)
    VFR = 750.0; % L/min
    CAa = 3.8; % mol/L
    Ta = 25 + 273.15; % K
    UA = 1500.0; % kJ/min/K
    dH = -79.8; % kJ/mol
    cP = 987.0 * 4.184e-3; % kJ/L/K
    fA = 0.8;
    nAa = VFR*CAa;
    
    % Case with backmix
    
    % Function that evaluates the equations
    function f = evalEqns(z)
        Tb = z(1);
        Td = z(2);
        [V,Tc] = Example_30_1_pfr(Tb);
        AMTD = 0.5*((Td-Ta) + (Tc-Tb));
        f = [
            VFR*cP*(Tb-Ta) - VFR*cP*(Tc-Td)
            VFR*cP*(Tb-Ta)- UA*AMTD
        ];
    end % of internal function evalEqns
    
    % guesses for the solution
    z_guess = [
        Ta + 25
        Ta + 50
    ];

    % Solve the set of algebraic equations
    z = fsolve(@evalEqns, z_guess);
    display('The solver found the following values for the unknowns:');
    z
    display('The corresponding values of the functions being solved are as follows:');
    f = evalEqns(z)
    
    Tb = z(1);
    [V,T] = Example_30_1_pfr(Tb);
    V_backmix = V
    
    % Case with no backmix, feed to reactor is at Ta
    [V,T]=Example_30_1_pfr(Ta);
    V_no_backmix = V
    	
end % of Example_30_1.m