Home > Blockchain >  Python: Create 2D Matrix of ascending integers in diagonal/triangle-like order with Numpy
Python: Create 2D Matrix of ascending integers in diagonal/triangle-like order with Numpy

Time:08-31

How do I create a matrix of ascending integers that are arrayed like this example of N=6?

1  3  6
2  5  0 
4  0  0

Here another example for N=13:

1  3  6  10 0
2  5  9  13 0
4  8  12 0  0
7  11 0  0  0
10 0  0  0  0

Also, the solution should perform well for large N values.

My code

import numpy as np
N = 13
array_dimension = 5
x = 0
y = 1
z = np.zeros((array_dimension,array_dimension))
z[0][0] = 1
for i in range(2, N 1):
    z[y][x] = i
    if y == 0:
        y = (x   1)
        x = 0
    else:
        x  = 1
        y -= 1
print(z)
[[ 1.  3.  6. 10.  0.]
 [ 2.  5.  9.  0.  0.]
 [ 4.  8. 13.  0.  0.]
 [ 7. 12.  0.  0.  0.]
 [11.  0.  0.  0.  0.]]

works, but there must be a more efficient way. Most likely via Numpy, but I cannot find a solution.

CodePudding user response:

My code

import numpy as np
N = 13
array_dimension = 5
x = 0
y = 1
z = np.zeros((array_dimension,array_dimension))
z[0][0] = 1
for i in range(2, N 1):
    z[y][x] = i
    if y == 0:
        y = (x   1)
        x = 0
    else:
        x  = 1
        y -= 1
print(z)
[[ 1.  3.  6. 10.  0.]
 [ 2.  5.  9.  0.  0.]
 [ 4.  8. 13.  0.  0.]
 [ 7. 12.  0.  0.  0.]
 [11.  0.  0.  0.  0.]]

works, but there must be a more efficient way. Most likely via Numpy, but I cannot find a solution.

CodePudding user response:

I didn't go into the depth of your code and try to write a better code, but just accelerating your code with numba library decorator can improve its efficiency much than twenty times (even hundreds):

import numpy as np
import numba as nb

@nb.njit
def new_(N, array_dimension):
    x = 0
    y = 1
    z = np.zeros((array_dimension,array_dimension))
    z[0][0] = 1
    for i in range(2, N 1):
        z[y][x] = i
        if y == 0:
            y = (x   1)
            x = 0
        else:
            x  = 1
            y -= 1
    return z

I will check again for writing better optimal code to improve its performance in the next day, if others do not suggest Until then.

  • Related