function plscrs = plscross(a, c, maxrank)
% PLSCROSS    Calculate CROSS as a function of the number of factors used
% Copyright (c) 1989-92 by The MathWorks, Inc.
%
%  plscrs = plscross(a, c, maxrank)
%
% Where:
%
%  plscrs    is the matrix containing cross
%  a         is the training set absorbance matrix
%  c         is the training set concentration matrix
%  maxrank   is optional limit to the number of factors tested
%

[i, j] = size(a);

if nargin == 3, i = maxrank; end

plscrs(i,1)=0;
for n = 1:j

x = a(:, [1:(n-1), (n+1):j])';
y = c(:, [1:(n-1), (n+1):j])';

k = 0;

for h = 1:i,
	u(:,h) = y(:,1);
	told(:,h) = zeros(j-1,1);
	t(:,h) = ones(j-1,1);
	while (sum(abs(told(:,h)-t(:,h)))) > (1e-10) & k < 100
		told(:,h) = t(:,h);
		k = k + 1;
		w(h,:)  = u(:,h)' * x / (u(:,h)' * u(:,h));
		w(h,:)  =  w(h,:) / sqrt(sum(w(h,:) .* w(h,:)));
		t(:,h)  = x * w(h,:)' / (w(h,:) * w(h,:)');
		q(h,:) = t(:,h)' * y / (t(:,h)' * t(:,h));
		u(:,h)  = y * q(h,:)'/ (q(h,:) * q(h,:)');
	end
        l(h) = k;
	k = 0;
p(h,:) = t(:,h)' * x / (t(:,h)' * t(:,h));
p(h,:) = p(h,:) / sqrt(sum(p(h,:) .* p(h,:)));
t(:,h)  = t(:,h) *  sqrt(sum(p(h,:) .* p(h,:)));
w(h,:)  = w(h,:) *  sqrt(sum(p(h,:) .* p(h,:)));
b(h) = (u(:,h)' * t(:,h)) / (t(:,h)' * t(:,h));
x = x - (t(:,h) * p(h,:));
y = y - (b(h) * t(:,h) * q(h,:));
end
for f = 1:i

	x = a(:,n)';
	cr = 0;
	for h=1:f
		tr(:,h) = x * w(h,:)';
		x = x - tr(:,h) * p(h,:);
		cr = cr + b(h) * tr(:,h) * q(h,:);
	end
	cr = cr';
	error = cr - c(:,n);
   	plscrs(f, 1) = plscrs(f, 1) + sum(sum(error .* error));

end
end
