Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to copy only upper triangular values into array from numpy.triu()?

Tags:

python

numpy

I have a square matrix A (could be any size) and I want to take the upper triangular part and place those values in an array without the values below the center diagonal (k=0).

A = array([[ 4,  0,  3],
           [ 2,  4, -2],
           [-2, -3,  7]])

using numpy.triu(A) gets me to

A = array([[ 4,  0,  3],
           [ 0,  4, -2],
           [ 0,  0,  7]])

but from here how would I copy only the upper triangular elements into a simply array? Such as:

[4, 0, 3, 4, -2, 7]

I was going to just iterate though and copy all non-zero elements, however zero's in the upper triangular are allowed.

like image 806
bynx Avatar asked Dec 17 '13 22:12

bynx


2 Answers

You can use Numpy's upper triangular indices function to extract the upper triangular of A into a flat array:

>>> A[np.triu_indices(3)]
array([ 4,  0,  3,  4, -2,  7])

And can easily convert this to a Python list:

>>> list(A[np.triu_indices(3)])
[4, 0, 3, 4, -2, 7]
like image 68
mdml Avatar answered Nov 15 '22 20:11

mdml


transform the upper/lower triangular part of a symmetric matrix (2D array) into a 1D array and return it to the 2D format

indices = np.triu_indices_from(A)
A = np.asarray( A[indices] )
like image 43
M4rtini Avatar answered Nov 15 '22 20:11

M4rtini