function X = bldCheb(npts, deg, renorm)
%  function X = bldCheb(npts, deg, renorm)
%  builds the design matrix X for univariate Chebychev
%  polynomial regression with design points {0, 1, ..., N-1},
%  for regression against the Chebychev polymonials of degree
%  d, 0 <= d <= deg.
%
%  If renorm is given and equals 1 (which is the default), 
%  renormalizes the Chebychev polymonials to unit l_2 norm.
%
%
%  Uses a two-term recursion from Abramowitz and Stegun,
%  Handbook of Mathematical Functions, Dover, 1965.
%
% P.B. Stark  stark@stat.berkeley.edu
% 10 July 1997.
%
if (deg < 0),
	error('maximum degree must be nonnegative')
end;
N = npts-1;
xpts = [0:N]';
X = ones(npts,1);
if (deg > 0),
	X = [X, X-(2/N)*xpts];
	for d = 2:deg,
		n = d-1;
		X = [X, ...
			((2*n+1)*(N - 2*xpts).* X(:,d) - ...
			n*(N+n+1)*X(:,d-1) )/((n+1)*(N-n)) ...
		    ];
	end;
end;

% normalize

rn = 1;
if (nargin == 3),
	rn = renorm;
end
if (rn == 1),
	for i=1:deg+1,
		X(:,i) = X(:,i)/norm(X(:,i));
	end;
end;

return
	

