meander shaped matrix in numpy in python

Here is a sample code to create and meander a numpy matrix in the shape of n x m:

main.py
import numpy as np

def meander_matrix(n, m):
    # create an n x m matrix with zeros
    mat = np.zeros((n, m), dtype=int)
    count = 1
    # set the starting position of the meandering
    row, col = 0, 0
    # set the initial direction to right
    direction = 1 
    
    # loop until all elements of the matrix are filled
    while count <= n * m:
        # set the current position with the count
        mat[row, col] = count
        
        # if moving right and hit the end of the row, switch to the next row and change direction
        if direction == 1 and col == m - 1:
            row += 1
            direction = -1
            
        # if moving left and hit the end of the row, switch to the next row and change direction
        elif direction == -1 and col == 0:
            row += 1
            direction = 1
            
        # if moving up and hit the end of the column, switch to the next column and change direction
        elif direction == -1 and row == 0:
            col += 1
            direction = 1
            
        # if moving down and hit the end of the column, switch to the next column and change direction
        elif direction == 1 and row == n - 1:
            col += 1
            direction = -1
            
        # update the position based on the direction
        else:
            row += direction
        
        count += 1
    
    return mat
1404 chars
44 lines

You can invoke the meander_matrix function to create a meandering matrix of a desired size:

main.py
mat = meander_matrix(5, 6)
print(mat)
38 chars
3 lines

This will output:

main.py
[[ 1  2  3  4  5  6]
 [12 11 10  9  8  7]
 [13 14 15 16 17 18]
 [24 23 22 21 20 19]
 [25 26 27 28 29 30]]
106 chars
6 lines

This matrix has 5 rows and 6 columns, with a meandering pattern.

gistlibby LogSnag