function a_inv = r8ut_inverse ( n, a )

%*****************************************************************************80
%
%% r8ut_inverse() computes the inverse of a R8UT matrix.
%
%  Discussion:
%
%    The R8UT storage format is used for an M by N upper triangular 
%    matrix.  The format stores all M*N entries, even those which are zero.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    18 March 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Alvert Nijenhuis, Herbert Wilf,
%    Combinatorial Algorithms,
%    Academic Press, 1978, second edition,
%    ISBN 0-12-519260-6
%
%  Input:
%
%    integer N, the order of the matrix.
%
%    real A(N,N), the matrix to be inverted.
%
%  Output:
%
%    real A_INV(N,N), the inverse matrix.
%

%
%  Check.
%
  for i = 1 : n
    if ( a(i,i) == 0.0 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'R8UT_INVERSE - Fatal error!\n' );
      fprintf ( 1, '  Zero diagonal element.\n' );
      error ( 'R8UT_INVERSE - Fatal error!' );
    end
  end

  a_inv(1:n,1:n) = a(1:n,1:n);

  for j = n : -1 : 1

    for i = n : -1 : 1

      if ( j < i )

        a_inv(i,j) = 0.0;

      elseif ( i == j )

        a_inv(i,j) = 1.0 / a_inv(i,j);

      elseif ( i < j )

        a_inv(i,j) = - ( a_inv(i,i+1:j) * a_inv(i+1:j,j) ) / a_inv(i,i);

      end

    end
  end

  return
end
