function [ D, x ] = cheb ( N )

%*****************************************************************************80
%
%% cheb() computes the Chebyshev differentiation matrix and grid.
%
%  Discussion:
%
%    Given a grid function v defined on the points of a Chebyshev grid,
%    the discrete derivative w is found by w = D * v.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    19 April 2020
%
%  Author:
%
%    Lloyd Trefethen
%
%  Reference:
%
%    Lloyd Trefethen,
%    Spectral methods in MATLAB,
%    SIAM, 2000,
%    LC: QA377.T65
%    ISBN: 978-0-898714-65-4
%
%  Input:
%
%    integer N: the number of grid points.
%
%  Output:
%
%    real D(N+1,N+1): the differentiation matrix.
%
%    real X(N+1): the Chebyshev grid.
%
  if ( N == 0 )
    D = []; 
    x = 1.0; 
    return, 
  end

  x = cos ( pi * (0:N) / N )'; 

  c = [ 2.0; ones(N-1,1); 2.0 ] .* (-1.0) .^ (0:N)';
  X = repmat ( x, 1, N+1 );
  dX = X - X';
%
%  Set offdiagonal entries.
%       
  D  = ( c * ( 1.0 ./ c )' ) ./ ( dX + ( eye ( N+1 ) ) );
%
%  Set diagonal entries.
%
  D  = D - diag ( sum ( D' ) );

  return
end
