%
% function [C] = DCT_BASIS( [N[, FACTOR]])
%
%          DCT_BASIS produces DCT basis functions
%              N is the length of the basis (defaults to 8 for demo)
%              FACTOR is an optional parameter just for smooth display
%              In case of no output parameter it just displays the basis
%

%
% Copyright © 08-Nov-2012 George P. Pavlidis® (sepdek@sepdek.net, gpavlid@gmail.com)
%
function varargout = dct_basis( varargin )

	switch nargin
		case 0
			N = 8;			% demo 8 point DCT
			factor = 10;
		case 1
			N = varargin{1};
			factor = 10;
		otherwise
			N = varargin{1};
			factor = varargin{2};
	end
	
	n=0:N-1;
	k=n;
	c = sqrt(2/N)*cos(k'*(2*n+1)*pi/(2*N));
	c(1,:) = c(1,:)/sqrt(2);
	c=c';
	
	% additional variables and sequences to produce smooth curves
	NN=factor*N;
	nn=0:NN-1;
	kk=nn;
	cc = sqrt(2/NN)*cos(kk'*(2*nn+1)*pi/(2*NN));
	cc(1,:) = cc(1,:)/sqrt(2);
	scale_factor = c(1)/cc(1);
	cc = scale_factor * cc;
	nnn = 0:factor:NN-1;
	cc=cc';

	switch nargout
		case 0
			if N==1,
				divider = 1;
			end;
			if N <= 20,
				figure( 'Name', sprintf('DCT BASE FOR N=%d',N));
				if mod(N,2)==0
					divider = 2;
				elseif mod(N,3)==0
					divider = 3;
				elseif mod(N,5)==0
					divider = 5;
				end
				for i=1:N
					subplot( divider, N/divider, i);
					stem( nnn+factor/2, c(:,i)); 
					grid on; axis tight; 
					title( sprintf('sequence #%d (k=%d)',i,i-1));
					hold on; plot( cc(:,i),'--r'); hold off;
				end
			else
				error( 'CANNOT DISPLAY %d BASIS FUNCTIONS IN ONE SCREEN!', N);
			end
		otherwise
			varargout{1} = c;
	end