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:
JavaScript
x
4
1
[[1 2 0]
2
[2 3 2]
3
[0 2 1]]
4
User input: n = 5
Output:
JavaScript
1
6
1
[[1 2 3 0 0]
2
[2 3 4 0 0]
3
[3 4 5 4 3]
4
[0 0 4 3 2]
5
[0 0 3 2 1]]
6
User input: n = 8
Output:
JavaScript
1
9
1
[[1 2 3 4 5 0 0 0]
2
[2 3 4 5 6 0 0 0]
3
[3 4 5 6 7 0 0 0]
4
[4 5 6 9 8 7 6 5]
5
[5 6 7 8 9 6 5 4]
6
[0 0 0 7 6 5 4 3]
7
[0 0 0 6 5 4 3 2]
8
[0 0 0 5 4 3 2 1]]
9
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!
JavaScript
1
8
1
def input_number(n):
2
matrix = np.zeros(shape=(n, n), dtype=int)
3
4
for y in range(round(n // 2) + 1):
5
for x in range(round(n // 2) + 1):
6
matrix[y, x] = x + y + 1
7
y += 1
8
Input: n = 4
Output:
JavaScript
1
6
1
[[1 2 3 0 0]
2
[2 3 4 0 0]
3
[3 4 5 0 0]
4
[0 0 0 0 0]
5
[0 0 0 0 0]]
6
Advertisement
Answer
I looked around a bit more and was eventually able to pull it off, here’s my take on it.
JavaScript
1
16
16
1
import numpy as np
2
3
4
def input_number(n):
5
matrix = np.zeros(shape=(n, n), dtype=int)
6
7
for y in range(round(n // 2) + 1):
8
for x in range(round(n // 2) + 1):
9
matrix[y, x] = y + x + 1
10
matrix[(n - y) - 1][(n - x) - 1] = matrix[y, x]
11
12
print(matrix)
13
14
15
input_number(n)
16
Input: 3
Output:
JavaScript
1
4
1
[[1 2 0]
2
[2 3 2]
3
[0 2 1]]
4
Input: 5
Output:
JavaScript
1
6
1
[[1 2 3 0 0]
2
[2 3 4 0 0]
3
[3 4 5 4 3]
4
[0 0 4 3 2]
5
[0 0 3 2 1]]
6
Input: 8
Output:
JavaScript
1
9
1
[[1 2 3 4 5 0 0 0]
2
[2 3 4 5 6 0 0 0]
3
[3 4 5 6 7 0 0 0]
4
[4 5 6 9 8 7 6 5]
5
[5 6 7 8 9 6 5 4]
6
[0 0 0 7 6 5 4 3]
7
[0 0 0 6 5 4 3 2]
8
[0 0 0 5 4 3 2 1]]
9