function A = magic4_matrix ( n )

%*****************************************************************************80
%
%% magic4_matrix() returns a magic matrix of n, where n is a multiple of 4.
%
%  Discussion:
%
%    Every row and column of the matrix has the same sum.
%
%    The algorithm proceeds as follows:
%
%    Number the cells consecutively, 1, 2, ..., n^2.
%    Divide the matrix into 4x4 blocks, draw an X in each block,
%    and in the x-ed out cells replace k by n^2+1-k.
% 
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    01 February 2025
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer n: the number of rows and columns in the matrix,
%    which must be a multiple of 4.
%
%  Output:
%
%    integer A(n,n): the magic matrix.
%
  if ( mod ( n, 4 ) ~= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'magic4_matrix(): Fatal error!\n' );
    fprintf ( 1, '  n = %d, but n must be a multiple of 4!', n );
  end

  A = zeros ( n, n );

  for i = 1 : n
    for j = 1 : n
      m1 = mod ( abs ( i - j     ), 4 );
      m2 = mod (     ( i + j - 1 ), 4 );
      k1 = ( i - 1 ) * n + j;
      k2 = n * n + 1 - k1;
      if ( ( m1 == 0 || m2 == 0 ) )
        A(i,j) = k2;
      else
        A(i,j) = k1;
      end
    end
  end

  return
end

