Vectorize matrix-vector product with multiple matrices of the same size (like np.linalg.solve does ...)
Hi everyone, I want to vectorize multiple matrix-vector products and avoid a for loop, a little bit like np.linalg.solve does, for instance : /nDOF = 100// //M = 4// // //mat = np.random.rand(nDOF, M, M)// //u = np.random.rand(nDOF, M)/ /vecMatInv = np.linalg.solve(mat, u) # => shape (nDOF, M) / /for i in range(nDOF):// // assert np.allclose(vecMatInv[i], np.linalg.solve(mat[i], u[i])) # => OK / This is quite straightforward and also works if u is only a flat vector of size M (which is great). But this is not that easy for matrix vector multiplication, and the solution I found yet is to use np.matmul with some manipulations over the array dimensions : vecMatMul = np.squeeze(np.matmul(mat, u[..., None]), axis=-1) /# => shape (nDOF, M)/ for i in range(nDOF): assert np.allclose(vecMatMul[i], mat[i] @ u[i]) # => OK That way we get the same behavior as for np.linalg.solve. But this seems not very natural, either for np.matmul or np.dot when using arrays of dimension > 2. Since np.linalg.solve does this vectorization naturally, I wonder if there is a way to get the same behavior with matrix-vector multiplication already in numpy, and why np.matmul does not behave like np.linalg.solve does ? Best, Thibaut -- *Dr. Thibaut LUNET* Chair Computational Mathematics, /Institute of Mathematics (E-10),/ /Office 3.040, tel: +49 40 42878 3428/ *Hamburg University of Technology*
On Wed, 2022-12-21 at 14:58 +0100, Thibaut Lunet wrote:
Hi everyone,
I want to vectorize multiple matrix-vector products and avoid a for loop, a little bit like np.linalg.solve does, for instance :
<snip>
dimension > 2.
Since np.linalg.solve does this vectorization naturally, I wonder if there is a way to get the same behavior with matrix-vector multiplication already in numpy, and why np.matmul does not behave like np.linalg.solve does ?
All of these functions need some convention to deal with ambiguity of matrix vs. stack of vector. Since we don't indicate it on the array itself, both matmul and the `@` operator assume matrix inputs unless given a vector. There have been thoughts of having a pair of `vecmat` and `matvec` functions to make working with stacked vectors more convenient. I don't think anyone ever pushed for it very strongly. There is maybe a bit more of a push for `vecdot` (both vectors) right now, but you want the mixed case... - Sebastian
Best,
Thibaut
_______________________________________________ NumPy-Discussion mailing list -- numpy-discussion@python.org To unsubscribe send an email to numpy-discussion-leave@python.org https://mail.python.org/mailman3/lists/numpy-discussion.python.org/ Member address: sebastian@sipsolutions.net
participants (2)
-
Sebastian Berg
-
Thibaut Lunet