function a = r8gd_dif2 ( n, ndiag, offset )

%*****************************************************************************80
%
%% R8GD_DIF2 sets up an R8GD second difference matrix.
%
%  Discussion:
%
%    The R8GD storage format is suitable for matrices whose only nonzero entries
%    occur along a few diagonals, but for which these diagonals are not all
%    close enough to the main diagonal for band storage to be efficient.
%
%    In that case, we assign the main diagonal the offset value 0.
%    Each successive superdiagonal gets an offset value 1 higher, until
%    the highest superdiagonal (the A(1,N) entry) is assigned the offset N-1.
%    Similarly, the subdiagonals are assigned offsets of -1 through -(N-1).
%
%    Now, assuming that only a few of these diagonals contain nonzeros,
%    then for the I-th diagonal to be saved, we stored its offset in
%    OFFSET(I), and its entries in column I of the matrix.  
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  Modified:
%
%    18 July 2016
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%
%    Input, integer NDIAG, the number of diagonals of the matrix
%    that are stored in the array.  
%    3 <= NDIAG.
%
%    Input, integer OFFSET(NDIAG), the offsets for the diagonal
%    storage.  The values -1, 0 and +1 should occur in OFFSET.
%
%    Output, real A(N,NDIAG), the R8GD matrix.
%
  if ( ndiag < 3 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8GD_DIF2 - Fatal error!\n' );
    fprintf ( 1, '  NDIAG must be at least 3.\n' );
    error ( 'R8GD_DIF2 - Fatal error!' );
  end

  a = zeros ( n, ndiag );

  for i = 1 : n
    for jdiag = 1 : ndiag
      j = i + offset(jdiag);
      if ( 1 <= j && j <= n )
        if ( offset(jdiag) == 0 )
          a(i,jdiag) = 2.0;
        elseif ( offset(jdiag) == -1 || offset(jdiag) == +1 )
          a(i,jdiag) = -1.0;
        end
      end
    end
  end

  return
end

