UberJumper
UberJumper

Reputation: 21145

Accessing Lower Triangle of a Numpy Matrix?

Okay, so basically lets say i have a matrix:

matrix([[0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4]])

Is it possible to get the area below the diagonal easily when working with numpy matrixs? I looked around and could not find anything. I can do the standard, for loop way however wouldnt that somehow invalidate the performance gave by numpy?

I am working on calculating statististics ofcomparing model output results with actual results. The data i currently have been given, results in around a 10,000 x 10,000 matrix. I am mainly trying to just sum those elements.

Is there an easy way to do this?

Upvotes: 4

Views: 3928

Answers (2)

Eric Humphrey
Eric Humphrey

Reputation: 179

def tri_flat(array):
    R = array.shape[0]
    mask = np.asarray(np.invert(np.tri(R,R,dtype=bool)),dtype=float)
    x,y = mask.nonzero()
    return array[x,y]

I was looking for a convenience function myself, but this'll have to do... not sure it gets much easier. But if it does, I'd be interested to hear it. Every time you avoid a for-loop, an angel gets its wings.

-ejh

Quick NB: This avoids the diagonal... if you want it, and your matrix is symmetric, just omit the inversion (elem-wise NOT). Otherwise, you'll need a transpose in there.

Upvotes: 2

Dmitry Kochkin
Dmitry Kochkin

Reputation: 993

You could use tril and triu. See them here: http://docs.scipy.org/doc/numpy/reference/routines.array-creation.html

Upvotes: 11

Related Questions