% MATLAB script file for extracting a complete independent subset from a
% set of linear equations or chemical reactions written in the form C*x = 0
%
% See Supplemental Unit S1 of "A First Course on Kinetics and Reaction
% Engineering" and/or the MATLAB documentation for additional information
% or if questions arise.
%
% Carl R. F. Lund, 4/22/13
%   last rev. 5/23/13
%
% Required input (must be present in the MATLAB workspace): 
%   C (matrix) - C(i,j) is the coefficient of variable x(j) in linear
%       equation i; the last column is the constant in equation i

% the number of independent equations is equal to the rank of C
n_ind = rank(C)
% get the total number of equations
n_total = size(C,1);

% The first equation (reaction) must be independent
IndEqs = C(1,:);
n_so_far = 1;
% loop through remaining equations (reactions)
for i = 2:n_total
    % test whether this equation (reaction) is independent
    temp = [IndEqs; C(i,:)];
    if rank(temp) > n_so_far
        % add this equation (reaction) to the independent subset
        IndEqs = temp;
        n_so_far = n_so_far + 1;
    end
end

% write out the independent equations (rows)
IndEqs

% End of IndEqns.m