function [ nz, row, col, diag, off ] = r8sr_dif2 ( n )

%*****************************************************************************80
%
%% R8SR_DIF2 sets up an R8SR second difference matrix.
%
%  Discussion:
%
%    The R8SR storage format stores the diagonal of a sparse matrix in DIAG.
%    The off-diagonal entries of row I are stored in entries ROW(I)
%    through ROW(I+1)-1 of OFF.  COL(J) records the column index
%    of the entry in A(J).
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  Modified:
%
%    10 June 2016
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%
%    Output, integer NZ, the number of offdiagonal nonzero elements
%    in the matrix.
%
%    Output, integer ROW(N+1).  The nonzero offdiagonal elements 
%    of row I of A are contained in A(ROW(I)) through A(ROW(I+1)-1).
%
%    Output, integer COL(NZ), contains the column index of the 
%    element in the corresponding position in A.
%
%    Output, real DIAG(N), the diagonal elements of A.
%
%    Output, real OFF(NZ), the off-diagonal elements of A.
%
  nz = 2 * n - 2;

  row = zeros ( n + 1, 1 );
  col = zeros ( nz, 1 );
  diag = zeros ( n, 1 );
  off = zeros ( nz, 1 );

  diag(1:n) = - 2.0;

  row(1) = 1;
  nz2 = 0;

  for i = 1 : n

    if ( i == 1 )

      nz2 = nz2 + 1;
      col(nz2) = i + 1;
      off(nz2) = 1.0;

      row(i+1) = row(i) + 1;

    elseif ( i < n )

      nz2 = nz2 + 1;
      col(nz2) = i - 1;
      off(nz2) = 1.0;

      nz2 = nz2 + 1;
      col(nz2) = i + 1;
      off(nz2) = 1.0;

      row(i+1) = row(i) + 2;

    else

      nz2 = nz2 + 1;
      col(nz2) = i - 1;
      off(nz2) = 1.0;

      row(i+1) = row(i) + 1;

    end

  end

  return
end
