Benjamin
Benjamin

Reputation: 11860

Numpy linalg on multidimensional arrays

Is there a way to use numpy.linalg.det or numpy.linalg.inv on an nx3x3 array (a line in a multiband image), for example? Right now I am doing something like:

det = numpy.array([numpy.linalg.det(i) for i in X])

but surely there is a more efficient way. Of course, I could use map:

det = numpy.array(map(numpy.linalg.det, X))

Any other more direct way?

Upvotes: 1

Views: 768

Answers (3)

Isabella
Isabella

Reputation: 401

New answer to an old question: Since version 1.8.0, numpy supports evaluating a batch of 2D matrices. For a batch of MxM matrices, the input and output now looks like:

linalg.det(a)
Compute the determinant of an array.

Parameters a(…, M, M) array_like
Input array to compute determinants for.

Returns det(…) array_like
Determinant of a.

Note the ellipsis. There can be multiple "batch dimensions", where for example you can evaluate a determinants on a meshgrid.

https://numpy.org/doc/stable/reference/generated/numpy.linalg.det.html

https://numpy.org/doc/stable/reference/generated/numpy.linalg.inv.html

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601539

I'm pretty sure there is no substantially more efficient way than what you have. You can save some memory by first creating an empty array for the results and writing all results directly to that array:

res = numpy.empty_like(X) 
for i, A in enumerate(X):
    res[i] = numpy.linalg.inv(A)

This won't be any faster, though -- it will only use less memory.

Upvotes: 3

yurib
yurib

Reputation: 8147

a "normal" determinant is only defined for a matrix (dimension=2), so if that's what you want i don't see another way.

if you really want to compute the determinant of a cube then you could try to implement one of the ways described here: http://en.wikipedia.org/wiki/Hyperdeterminant

notice that it is not necessarily the same value as the one you're currently computing.

Upvotes: 1

Related Questions