function [ U, X, Y ] = poisson ( nx, ny, xmin, xmax, ymin, ymax, f, g )

%*****************************************************************************80
%
%% poisson is a simple program to solve a Poisson equation in a rectangle.
%
%  Discussion:
%
%    This program uses the finite difference method to estimate the solution
%    to a Poisson problem on a rectangle:
%
%      - Del U = f(x,y) in Omega
%            U = g(x,y) on dOmega
%
%    The user specifies the number of grid points (nx,ny), the spatial
%    extent (xmin,xmax,ymin,ymax), and the functions f(x,y), g(x,y).
%
%    No attempt is made to efficiently construct the matrix, or to store
%    it sparsely.
%
%  Modified:
%
%    17 September 2019
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer NX, NY, the number of grid points in the X and Y directions.
%
%    real XMIN, XMAX, YMIN, YMAX, the X and Y endpoints.
%
%    function handle F, the name of the MATLAB function which evaluates
%    the right hand side of the Poisson equation.
%
%    function handle G, the name of the MATLAB function which evaluates
%    the Dirichlet boundary conditions.
%
%  Output:
%
%    real U(NY,NX), a table of solution values.
%
%    real X(NY,NX), Y(NY,NX), tables of the X and Y coordinates of the points.
%

%
%  Compute the X and Y spacings.
%
  hx = ( xmax - xmin ) / ( nx - 1 );
  hy = ( ymax - ymin ) / ( ny - 1 );
%
%  Compute the X and Y coordinate vectors.
%
  x = linspace ( xmin, xmax, nx );
  y = linspace ( ymin, ymax, ny );
%
%  Set the system matrix A and right hand side rhs.
%
  A = zeros ( nx * ny, nx * ny );
  rhs = zeros ( nx * ny, 1 );

  keq = 0;
  for j = 1 : ny
    for i = 1 : nx
      keq = keq + 1;
      if ( i == 1 || i == nx || j == 1 || j == ny )
        A(keq,keq) = 1.0;
        rhs(keq) = g ( x(i), y(j) );
      else
        A(keq,keq) = 2.0 / hx / hx + 2.0 / hy / hy;
        A(keq,keq-1)  = - 1.0 / hx / hx;
        A(keq,keq+1)  = - 1.0 / hx / hx;
        A(keq,keq-nx) = - 1.0 / hy / hy;
        A(keq,keq+nx) = - 1.0 / hy / hy;
        rhs(keq) = f ( x(i), y(j) );
      end
    end
  end
%
%  Solve for u, the solution vector.
%
  u = A \ rhs;
%
%  Return matrices U, X, Y.
%
  U = ( reshape ( u, nx, ny ) )';
  [ X, Y ] = meshgrid ( x, y );

  return
end

