Skip to content
Advertisement

Python Numpy make a pattern with a square matrix of any dimension

I am having difficulties trying to generate a specific pattern that would work for any square matrix with any square dimension using NumPy

For example:

User input: n = 3

Output:

[[1 2 0]
 [2 3 2]
 [0 2 1]]

User input: n = 5

Output:

[[1 2 3 0 0]
 [2 3 4 0 0]
 [3 4 5 4 3]
 [0 0 4 3 2]
 [0 0 3 2 1]]

User input: n = 8

Output:

[[1 2 3 4 5 0 0 0]
 [2 3 4 5 6 0 0 0]
 [3 4 5 6 7 0 0 0]
 [4 5 6 9 8 7 6 5]
 [5 6 7 8 9 6 5 4]
 [0 0 0 7 6 5 4 3]
 [0 0 0 6 5 4 3 2]
 [0 0 0 5 4 3 2 1]]

Since a square matrix can be generated with any number in the form of (n x n), there would be instances where the user input is an odd number, how would I start figuring out the equations needed to make this work?


I got this going on but I was only able to do it on one corner of the matrix, any suggestion or idea is appreciated, thank you!

def input_number(n):
    matrix = np.zeros(shape=(n, n), dtype=int)

    for y in range(round(n // 2) + 1):
        for x in range(round(n // 2) + 1):
            matrix[y, x] = x + y + 1
        y += 1

Input: n = 4

Output:

[[1 2 3 0 0]
 [2 3 4 0 0]
 [3 4 5 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]

Advertisement

Answer

I looked around a bit more and was eventually able to pull it off, here’s my take on it.

import numpy as np


def input_number(n):
    matrix = np.zeros(shape=(n, n), dtype=int)

    for y in range(round(n // 2) + 1):
        for x in range(round(n // 2) + 1):
            matrix[y, x] = y + x + 1
            matrix[(n - y) - 1][(n - x) - 1] = matrix[y, x]

    print(matrix)


input_number(n)

Input: 3

Output:

[[1 2 0]
 [2 3 2]
 [0 2 1]]

Input: 5

Output:

[[1 2 3 0 0]
 [2 3 4 0 0]
 [3 4 5 4 3]
 [0 0 4 3 2]
 [0 0 3 2 1]]

Input: 8

Output:

[[1 2 3 4 5 0 0 0]
 [2 3 4 5 6 0 0 0]
 [3 4 5 6 7 0 0 0]
 [4 5 6 9 8 7 6 5]
 [5 6 7 8 9 6 5 4]
 [0 0 0 7 6 5 4 3]
 [0 0 0 6 5 4 3 2]
 [0 0 0 5 4 3 2 1]]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement