Triangles in Numpy Arrays

NumPy is a mighty Python library, which adds support for multi-dimensional arrays and matrices besides many efficient mathematical functions. I have some handy new tricks using this library that I want to share with you. In this post, I will show how to operate with matrix triangles using NumPy easily.

So, let’s start creating a 4×4 matrix:

In: my_matrix = np.arange(16).reshape(4, 4)
Out: array([ 0, 1, 2, 3],
           [ 4, 5, 6, 7,],
           [ 8, 9, 10, 11],
           [12, 13, 14, 15]])

We can easily get the diagonal of the matrix, using the diagonal method:

In: my_matrix.diagonal()

Out: array([[ 0, 5, 10, 15])

Then, the most important step is to apply the function np.tril_indices to get the indices related to the matrix\’s diagonals. We also used the “k=1” option to exclude the diagonal terms.

In: tril_my_matrix = np.tril_indices(my_matrix.diagonal().size, k=-1)

Out: (array([[ 1, 2, 2, 3, 3, 3]), array([0, 0, 1, 0, 1, 2]))

Once we obtained the indices for both lower and upper triangles, we can select these items in the matrix. For the lower triangle, we have:

In: my_matrix[tril_my_matrix[0], tril_my_matrix[1]]

And for the upper triangle:

In: my_matrix[tril_my_matrix[1], tril_my_matrix[0]]

Out: array([ 1, 2, 6, 3, 7, 11])

And to finish it, we can unpack the triangles in a zero matrix to easily create new triangle matrices:

In: zero_matrix = np.zeros((4, 4))

Out: array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])

Note that we apply the method copy() when copying items in an array. It is needed when we want to keep the original list unchanged after the new list is modified. We applied the indices obtained to select only the items of the triangles.

In: lower_triangle = zero_matrix.copy() lower_triangle[tril_my_matrix[0], tril_my_matrix[1]] = my_matrix[tril_my_matrix[0], tril_my_matrix[1]].copy()

Out: array([[ 0., 0., 0., 0.], [ 4., 0., 0., 0.], [ 8., 9., 0., 0.], [12.,13.,14., 0.]])

In: upper_triangle = zero_matrix.copy() upper_triangle[tril_my_matrix[1], tril_my_matrix[0]] = my_matrix[tril_my_matrix[1], tril_my_matrix[0]].copy()

Out: array([[ 0., 1., 2., 3.],
[ 0., 0., 6., 7.],
[ 0., 0., 0.,11.],
[ 0., 0., 0., 0.]])

That’s it! It seems so simple now, isn’t it? If you have any questions or suggestions, just leave a comment!

Best regards and stay safe!

3 thoughts on “Triangles in Numpy Arrays”

  1. Pingback: Off-White x Air Max 97 OG 'Black' Reps

  2. Pingback: Fake Yeezy Boost 350 V2 'Lundmark'

  3. Pingback: Travis Scott x Air Jordan 1 Low 'Mocha' Reps

Comments are closed.