Dario
Dario

Reputation: 331

Python: extract upper triangular part of a matrix and put it back

I have a square matrix A, whith n rows and n columns.

I extracted the upper triangular part of the matrix:

Arr = A[np.triu_indices(n, k = 1)]

I've made some operations on the array Arr and I would now like to rebuild a nxn matrix from this array, putting each element to the original position it belonged to and setting to zero all the other elements of the matrix.

How can I do that?

Upvotes: 0

Views: 670

Answers (1)

MichaelCG8
MichaelCG8

Reputation: 579

So Arr is the upper triangular portion, you modify it, then put it in a new matrix where that is the upper portion and the rest is zeros?

Try this:

upper_indices = np.triu_indices(n, k = 1)
Arr = A[upper_indices]

# Do stuff with Arr

result = np.zeros((n, n))
result[upper_indices] = modified_Arr

Upvotes: 2

Related Questions