function dvdx = cdiff(v,x)
% dvdx = cdiff(v,x)
%
% Numerical differentiation of a vector using central differences. 
%
%   cdiff(v)     presumes uniform unit spacing of elements in the vector v
%   cdiff(v,dx)  where dx is scalar presumes uniform spacing of of dx 
%   cdiff(v,x)   where length(x) = length(v) presumes v is sampled at points x
%
%   cdiff uses central differences, except on the end points where a
%   forward / backward difference is used.  length(dvdx) = length(v)

 n = size(v,2);

 if ( nargin == 2 ) 
	if ( length(x) == n )
		dx = x;
		dx(1)     =  x(2) - x(1);
		dx(2:n-1) =  0.5 * ( x(3:n)-x(1:n-2) ); 
		dx(n)     =  x(n) - x(n-1);
	end
	if ( length(x) == 1 )
		dx = x;
	end
 else
	dx = 1.0;
 end

 dv = v;
 dv(:,1)     =  v(:,2)   - v(:,1);
 dv(:,2:n-1) =  0.5*( v(:,3:n) - v(:,1:n-2) ); 
 dv(:,n)     =  v(:,n) - v(:,n-1);

 dvdx = dv ./ dx;

% cdiff ------------------------------------------------------- 30 Mar 2011

