Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy Matrix Multiplication Simplification - is it possible?

Is there a way to simplify

 a=np.dot(a,b)

just like the way you write a=a+b as a+=b ? (a,b are both np.array)

like image 316
Yuan Chen Avatar asked Jan 30 '26 21:01

Yuan Chen


1 Answers

In Python3.5+ you can use the @ operator for matrix multiplication, e.g.:

import numpy as np

a = np.random.randn(4, 10)
b = np.random.randn(10, 5)

c = a @ b

This is equivalent to calling c = np.matmul(a, b). Inplace matrix multiplication (@=) is not yet supported (and doesn't make sense in most cases anyway, since the output usually has different dimensions to the first input).

Also note that np.matmul (and @) will behave differently to np.dot when one or more of the input arrays has >2 dimensions (see here).

like image 113
ali_m Avatar answered Feb 02 '26 09:02

ali_m