开发者

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜