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

Viewed 60

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]
1 Answers

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)
Related