0

I have several arrays in a list (think of it as a time series):

one_array = np.array([[1, 2, 3],[5,5,5],[0,0,1]])
many_arrays = np.array([one_array, one_array + 1])

Now, I want to do the same operation for every matrix in the time series, e.g. I want to calculate the determinant. These two operations give the same result (-5):

np.linalg.det(one_array)
np.linalg.det(many_arrays[0,:,:])

How do I tell Python to do np.linalg.det(many_arrays[i,:,:]) for every i without used the dreaded loop? So in this particular example I'd like to get (-5, -6) as a return value.

Bonus points: How can I tell Python to do np.linalg.det(even_more_arrays[i, j, :,:]) for every i, j?


edit: I am looking for a generic way to do this. I understand that np.linalg.det supports this operation. But how do I do it for any function DO_SOMETHING_WITH_2D_MATRIX that only takes a 2 dimensional object:

DO_SOMETHING_WITH_2D_MATRIX(one_array)
DO_SOMETHING_WITH_2D_MATRIX(many_arrays[0,:,:])
don-joe
  • 600
  • 1
  • 4
  • 12
  • You might want to check this: https://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array – qmeeus Aug 11 '20 at 10:30

1 Answers1

1

Simply use:

np.linalg.det(many_arrays)

'''
Output:
array([-5., -6.])
'''

without slicing many_arrays.

As,

many_arrays[0,:,:] = one_array

Rahul Vishwakarma
  • 1,446
  • 2
  • 7
  • 22
  • OK, yes, that works. But it works because of some np-magic there, that supports that kind of operation. Suppose I write my own determinant-function. How do I write it in a way that this works? – don-joe Aug 11 '20 at 13:26
  • That's not magic, you should read NumPy documentation. For writing your own determinant-function, you should try by yourself first. Then if you get any problem/errors, then ask (making a new question for that will be good). – Rahul Vishwakarma Aug 11 '20 at 13:30
  • Thanks you for helping! I think I have not clearly stated my problem. I am NOT interested in calculating the determinant. I am interested in what I called "magic" just before. Maybe you can point me to where to look that up in the NumPy documentation? Because I have not been able to find it. – don-joe Aug 11 '20 at 13:35
  • [Look up here](https://numpy.org/doc/stable/user/quickstart.html#indexing-slicing-and-iterating) – Rahul Vishwakarma Aug 11 '20 at 13:38