def magic_matrix ( n ): #*****************************************************************************80 # ## magic_matrix() returns a magic matrix of odd order n as a numpy array. # # 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: # # 22 January 2023 # # Author: # # Original Python version by Christian Hill. # This version by John Burkardt. # # Reference: # # Christian Hill, # Learning Scientific Programming with Python, # Cambridge University Press, # Second Edition, 2020, # ISBN: 978-1108745918 # # Input: # # integer n: the number of rows and columns in the matrix, # which must be odd. # # Output: # # integer A(n,n): the magic matrix. # import numpy as np if ( ( n % 2 ) != 1 ): print ( '' ) print ( 'magic_matrix(): Fatal error!' ) print ( ' Input value n must be an odd integer.' ) raise Exception ( 'magic_matrix(): Fatal error!' ) A = np.zeros ( [ n, n ], dtype = int ) k = 1 i = 0 j = n // 2 while ( k <= n**2 ): A[i,j] = k k = k + 1 new_i = ( i - 1 ) % n new_j = ( j + 1 ) % n if ( A[new_i,new_j] ): i = i + 1 else: i = new_i j = new_j return A