function cross = pcrcross(a, c, vc, maxrank)
% PCRCROSS  Calculate cross-validation for standards.
%
%             PCRCROSS calculates cross-validation for standards
%             as a function of the number of factors used.
%
%  cross = pcrcross(a, c, vc, maxrank)
%
% Where:
%
%  cross    is the matrix containing information on the cross-validation
%  a        is the absorbance matrix
%  c        is the concentration matrix
%  vc       is the matrix containing the eigenvectors (factors)
%  maxrank  is optional limit to the number of factors tested
%
% cross contains the squares of the error for the
% cross-validation on the standard set by leaving out one standard
% at a time and treating it as an unknown.
%

% Copyright (c) 1989-92 by The MathWorks, Inc.

[i, j] = size(vc);
cross(i,1)=0;

if nargin == 4, i = maxrank; end

for n = 1:i
   factors = vc(:, 1:n);
   [k, l] = size(a);
   for p = 1:(l - 1);
      proj = factors' * a(:, [1:(p-1), (p+1):l]);
      f = c(:, [1:(p-1), (p+1):l]) * proj' * inv(proj*proj') * factors';
      error = (f * a(:, p)) - c(:, p);
      errorsq(p) = sum(error .* error);
   end
   cross(n) = sum(errorsq);
end
