I would like to get indices for an upper triangle matrix. I am aware of np.triu_indices, but cannot use it in my application at the moment.
I can get its values from the below code, but not sure how to get its indices.
Please advice
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in range(len(matrix)):
print(matrix[i][i+1:]) # For excluding the main diagonal elems
In the above example, I would like the indices for 2, 3, and 6
You already have the indices, you're using them to access elements in matrix
Instead of using them to index into matrix
, add them to a list:
row_indices = []
col_indices = []
for i in range(len(matrix)):
row = matrix[i]
col_ix = list(range(i+1, len(row)))
row_ix = [i] * len(col_ix)
row_indices.extend(row_ix)
col_indices.extend(col_ix)
Now row_indices
and col_indices
contain the indices you're looking for.