function exercise2 ( )

%*****************************************************************************80
%
%% exercise2 set up and solve a Poisson equation.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 July 2020
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'exercise2:\n' );
  fprintf ( 1, '  Set up and solve a 1D Poisson equation.\n' );

  a = -2.0;
  b = +2.0;

  n = 5;
  x = linspace ( a, b, n );
  h = ( b - a ) / ( n - 1 );

  A = zeros ( n, n );
  rhs = zeros ( n, 1 );

%at x1 = -2:        u1        =   x1^3 = -8

  A(1,1) = 1.0;
  rhs(1) = g(x(1));

%at x2 = -1: -u1 + 2u2 - u3   = -6x2   =  6
%at x3 =  0: -u2 + 2u3 - u4   = -6x3   =  0
%at x4 = +1: -u3 + 2u4 - u5   = -6x4   = -6

  for i = 2 : n - 1

    A(i,i-1) = -1.0 / h^2;
    A(i,i)   =  2.0 / h^2;
    A(i,i+1) = -1.0 / h^2;

    rhs(i) = f(x(i));

  end

%at x5 = +2:        u5        =   x5^3 =  8

  A(n,n) = 1.0;
  rhs(n) = g(x(n));
%
%  Solve.
%
  u = A \ rhs;

  x2 = linspace ( a, b, 101 );
  plot ( x, u, 'ro', x2, g(x2), 'b-', 'linewidth', 3 );

  print ( '-dpng', 'exercise2.png' );

  return
end
function value = g ( x )

%*****************************************************************************80
%
  value = x.^3;
  return
end

function value = f ( x )

%*****************************************************************************80
%
  value = - 6*x;
  return
end
