function sp=spap2(knots,k,x,y)
% SPAP2	Least-squares approximation by splines.
%
%         spap2(knots,k,x,y)
%
%  returns the spline  f  of order  k  with knot sequence  knots  for which
%
%  (*)                y = f(x) 
%
% in the mean-square sense. If the abscissae satisfy the conditions
%
%  (**)   knots(j) < x(j) < knots(j+k) , j=1,...,length(x)=length(knots)-k ,
%
%  f  is the unique spline of that order satisfying  (*)  exactly.
% No spline is returned unless (**) is satisfied for some subsequence of  x .

% C. de Boor / latest change: December 24, 1989
% Copyright (c) 1990-92 by Carl de Boor and The MathWorks, Inc.


% It is assumed that  y  has the same sense as  x  which is important in case
% the entries of  y  are vectors rather than scalars
[rx,cx]=size(x); [ry,cy]=size(y);
if (rx>1),
   if (ry~=rx), error(' y  should contain exactly as many entries as  x ')
   else, y=y';end
else,
   if (cy~=cx), error(' y  should contain exactly as many entries as  x ')
   end
end

%  sort the given abscissae.
[x,index]=sort(x);y=y(:,index);

%  Generate the collocation matrix and divide it into the possibly reordered
%  sequence of given ordinates to generate the B-spline coefficients of the 
%  interpolant, then put it all together into  sp .

sp=spmak(knots,slvblk(spcol(knots,k,x,1),y')');
