Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trace of each matrix in a numpy array

Tags:

python

numpy

Given a list of multiple matrices, I want to compute the trace of each matrix.

np.asarray([[[1,2,3],
             [4,5,6],
             [7,8,9]],
           [[10,11,12],
            [13,14,15],
            [16,17,18]]])

The result should be:

np.asarray([15, 42])
like image 507
St123 Avatar asked Mar 25 '26 04:03

St123


2 Answers

Use axis1=1 and axis2=2 arguments in np.trace.

np.trace(x, axis1=1, axis2=2)

like image 114
shivammittal99 Avatar answered Mar 26 '26 16:03

shivammittal99


Here's a way using advanced indexing and sum along the second axis:

a = np.asarray([[[1,2,3],
                 [4,5,6],
                 [7,8,9]],
               [[10,11,12],
                [13,14,15],
                [16,17,18]]])

a[:, range(a.shape[1]), range(a.shape[2])].sum(1)
# array([15, 42])
like image 45
yatu Avatar answered Mar 26 '26 16:03

yatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!