% MATLAB file used in the solution of Example 14.2 of 
% "A First Course on Kinetics and Reaction Engineering."

% Data provided in the problem statement, in consistent units
V=2.3; % L
T=848.0; % K
P0=1036.0; % Torr
Rgas=62.366; % L-Torr/mol/K
t = [0; 0.1; 0.2; 0.3; 0.4; 0.5; 0.6; 0.7; 0.8; 0.9; 1.0]; % ms
Pz = [0; 121; 202; 275; 336; 375; 417; 416; 433; 457; 476]; % Torr

% calculate nA using equation (15) from the solution.
nA = V/Rgas/T*(P0 - 2*Pz);

% fit third order polynomials to the nA vs t data
p = polyfit(t,nA,3);

% use its derivative to estimate dnA/dt
dnAdt_poly = 3*p(1)*t.*t + 2*p(2)*t + p(3);

% use forward differences to estimate dnA/dt for all but the last point
dnAdt_fd =zeros(10,1);
for i = 1:10
    dnAdt_fd(i) = (nA(i+1)-nA(i))/(t(i+1)-t(i));
end

% solve part (a) of the problem
disp('part (a)');

%fit using forward differences (there's one less data point)
disp('forward differences results');
x = -nA(1:10);
y_hat = dnAdt_fd;
figure;
% Use the MATLAB script file "FitLinmSR.m" from "A First Course on
% Kinetics and Reaction Engineering" to fit a straight line through the
% origin to the data here and below
FitLinmSR;
title('Part (a) using forward differences');

% fit using the polynomial method
disp('polynomial method results');
x = -nA;
y_hat = dnAdt_poly;
figure;
FitLinmSR;
title('Part (a) using polynomial method');

% solve part (b) of the problem
disp('part (b)');

%fit using forward differences (there's one less data point)
disp('forward differences results');
x = -(nA(1:10).^2)/V;
y_hat = dnAdt_fd;
figure;
FitLinmSR;
title('Part (b) using forward differences');

% fit using the polynomial method
disp('polynomial method results');
x = -(nA.^2)/V;
y_hat = dnAdt_poly;
figure;
FitLinmSR;
title('Part (b) using polynomial method');

