function [ nz, ija, a ] = r8ri_dif2 ( n )

%*****************************************************************************80
%
%% R8RI_DIF2 stores the second difference matrix in R8RI format.
%
%  Discussion:
%
%    An R8RI matrix is in row indexed sparse storage form, using an index
%    array IJA and a value array A.  The first N entries of A store the
%    diagonal elements in order.  The first N entries of IJA store the index
%    of the first off-diagonal element of the corresponding row; if there is
%    no off-diagonal element in that row, it is one greater than the index
%    in A of the most recently stored element in the previous row.
%    Location 1 of IJA is always equal to N+2; location N+1 of IJA is one
%    greater than the index in A of the last off-diagonal element of the
%    last row.  Location N+1 of A is not used.  Entries in A with index
%    N+2 or greater contain the off-diagonal values, ordered by row, and
%    then by column.  Entries in IJA with index N+2 or greater contain the
%    column number of the corresponding element in A.
%
%  Example:
%
%    A:
%      3 0 1 0 0
%      0 4 0 0 0
%      0 7 5 9 0
%      0 0 0 0 2
%      0 0 0 6 8
%
%    NZ = 11
%
%    IJA:
%      7  8  8 10 11 12  3  2  4  5  4
%
%    A:
%      3  4  5  0  8  *  1  7  9  2  6
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    06 July 2016
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    William Press, Brian Flannery, Saul Teukolsky, William Vetterling,
%    Numerical Recipes in FORTRAN: The Art of Scientific Computing,
%    Third Edition,
%    Cambridge University Press, 2007,
%    ISBN13: 978-0-521-88068-8,
%    LC: QA297.N866.
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%
%    Input, integer NZ, the size required for the RI
%    or "row indexed" sparse storage.  NZ = 3*N-1.
%
%    Output, integer IJA(NZ), the index vector.
%
%    Output, real A(NZ), the value vector.
%
  nz = 3 * n - 1;
  ija = zeros ( nz, 1 );
  a = zeros ( nz, 1 );
%
%  Diagonal elements of A.
%
  a(1:n) = 2.0;
%
%  First N entries of IJA store first offdiagonal of each row.
%
  k = n + 2;

  for i = 1 : n
    ija(i) = k;
    if ( i == 1 || i == n )
      k = k + 1;
    else
      k = k + 2;
    end
  end
%
%  IJA(N+1) stores one beyond last element of A.
%
  ija(n+1) = k;
  a(n+1) = 0.0;
%
%  IJA(N+2), A(N+2) and beyond store column and value.
%
  k = n + 1;

  for i = 1 : n

    if ( i == 1 )
      k = k + 1;
      ija(k) = i + 1;
      a(k) = - 1.0;
    elseif ( i < n )
      k = k + 1;
      ija(k) = i - 1;
      a(k) = - 1.0;
      k = k + 1;
      ija(k) = i + 1;
      a(k) = - 1.0;
    elseif ( i == n )
      k = k + 1;
      ija(k) = i - 1;
      a(k) = - 1.0;
    end

  end

  return
end
