Phil
Phil

Reputation: 13

Iterate through upper triangular matrix in Python

I am using Python and I have a XxY matrix where X=Y and I want to iterate over the upper triangular matrix in a specific way such that it starts with enter image description here and proceeds with enter image description here and enter image description here and so on and so forth until the last row and column. Therefore, I tried to create a double loop which loops over the columns one by one and within that loop I created another loop which loops over the rows always adding one row. However, I got stuck in defining how to add the next row for every column in the second loop. Here is what I got so far (for simplicity I just created an array of zeros):

import pandas as pd
import numpy as np

# number of columns
X = 10
# number or rows
Y = X

U = np.zeros((Y,X))

for j in range(X):
    for z in range():

My initial idea was to create an array of Yx1 with y = np.asarray(list(range(0,Y)))and use it for the second loop but I don't understand how to implement it. Can somebody please help me? Is there maybe a simpler way to define such an iteration?

Upvotes: 0

Views: 3851

Answers (1)

Mark
Mark

Reputation: 92430

With Numpy, you can get the indices for the upper triangular matrix with triu_indices_from and index into the array with that:

import numpy as np

a = np.arange(16).reshape([4, 4])
print(a)
#[[ 0  1  2  3]
# [ 4  5  6  7]
# [ 8  9 10 11]
# [12 13 14 15]]

indices = np.triu_indices_from(a)

upper = a[indices]
print(upper)
# [ 0  1  2  3  5  6  7 10 11 15]

Upvotes: 1

Related Questions