function A = magic_matrix ( n )

%*****************************************************************************80
%
%% magic_matrix() returns a magic matrix of odd order n.
%
%  Discussion:
%
%    Every row and column of the matrix has the same sum.
%
%    The algorithm proceeds as follows:
%
%    a) Start in the middle of the top row, and let k = 1;
%    b) Insert k into the grid.
%    c) If k = n^2, you are done.
%    d) Increment k.
%    e) Move diagonally up and to the right, but wrap to the first
%       column, or to the last row, if you leave the grid.
%    f) If that cell is already occupied, drop down one space from
%       your current position.
%    g) Return to step (b).  
% 
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    05 December 2022
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer n: the number of rows and columns in the matrix,
%    which must be odd.
%
%  Output:
%
%    integer A(n,n): the magic matrix.
%
  if ( mod ( n, 2 ) ~= 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'magic_matrix(): Fatal error!\n' );
    fprintf ( 1, '  Input value n must be an odd integer.\n' );
    error ( 'magic_matrix(): Fatal error!\n' );
  end

  A = zeros ( n, n );

  k = 1;
  i = 1;
  j = ( n + 1 ) / 2;
  A(i,j) = k;

  while ( k < n^2 )

    k = k + 1;

    im1 = mod ( i - 2, n ) + 1;
    jp1 = mod ( j, n ) + 1;
    if ( A(im1,jp1) ~= 0 )
      im1 = i + 1;
      jp1 = j;
    end

    A(im1,jp1) = k;
    i = im1;
    j = jp1;

  end

  return
end

