2

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)

ali_m
  • 71,714
  • 23
  • 223
  • 298
Yuan Chen
  • 87
  • 1
  • 3
  • 2
    Nope. There isn't a shortcut here ... – mgilson May 24 '16 at 21:15
  • You could create a wrapper class around `numpy.matrix` and overload the `*` operator, but that'd be very confusing and definitely discouraged. What's wrong with `np.dot`? – Rushy Panchal May 24 '16 at 21:21
  • 1
    Well, I am just trying to save my runtime since a and b could be large in size. – Yuan Chen May 24 '16 at 21:32
  • 1
    What is the run time savings of `+=` for your size of arrays? – hpaulj May 24 '16 at 22:00
  • @Rushy Panchal What's wrong with it is that it uses six characters to express what should be done with a single character. In a lengthier calculation, it's just plain tedious to read all those "np.dot". It slows one's brain down from taking in the meaning of the equation. – Michael Tuchman May 11 '20 at 20:41

1 Answers1

15

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

Community
  • 1
  • 1
ali_m
  • 71,714
  • 23
  • 223
  • 298