简体   繁体   中英

how to apply a function (matrix -> scalar) to 3 dim a numpy array in python

Say I have 3 dimensional numpy array a , for example as below:

import numpy as np
a = np.random.randn(3, 3, 3)

How can I apply (matrix->scalar)-type function to a ? More specifically, I want to do an equivalent thing as below in a more computationally efficient way:

[np.linalg.det(e) for e in a]

np.linalg.det(a) seems to work just fine and has significantly better runtime:

a = np.random.rand(100,3,3)

%timeit -n 100 [np.linalg.det(e) for e in a]
626 µs ± 26.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit -n 100 np.linalg.det(a)
33.9 µs ± 7.08 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM