function [x,r,A,condA] = expfit(alpha,t,y)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [x,r,A,condA] = expfit(alpha,t,y)
% Given the rate constants alpha, expfit determines the 
% linear coefficients in the exponential fitting of the
% data y taken at times t.
% On return:
%    x is the vector of linear coefficients
%    r is the vector of data residuals:
%       observed y - model
%    A is the matrix in the least squares problem
%    condA is the condition number of A
%
%  expfit.m Dianne P. O'Leary   02/04 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Compute the matrix A, its SVD, and its condition number.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for j=1:length(alpha)
   A(:,j) = exp(alpha(j)*t);
end

[m,n] = size(A);
[u,s,v] = svd(A);
if (n>1)
   s = diag(s);
else
   s = s(1,1);
end
condA = s(1)/s(n);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Compute the solution to the least squares problem
% and the residual.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

w = (u(:,1:n)'*y) ./ s;
x = v*w;
r = y - A*x;
