Vectorized way of calculating row-wise dot product two matrices with Scipy

Straightforward way to do that is: import numpy as np a=np.array([[1,2,3],[3,4,5]]) b=np.array([[1,2,3],[1,2,3]]) np.sum(a*b, axis=1) which avoids the python loop and is faster in cases like: def npsumdot(x, y): return np.sum(x*y, axis=1) def loopdot(x, y): result = np.empty((x.shape[0])) for i in range(x.shape[0]): result[i] = np.dot(x[i], y[i]) return result timeit npsumdot(np.random.rand(500000,50),np.random.rand(500000,50)) # 1 loops, best of 3: … Read more

how does multiplication differ for NumPy Matrix vs Array classes?

The main reason to avoid using the matrix class is that a) it’s inherently 2-dimensional, and b) there’s additional overhead compared to a “normal” numpy array. If all you’re doing is linear algebra, then by all means, feel free to use the matrix class… Personally I find it more trouble than it’s worth, though. For … Read more

Difference between numpy dot() and Python 3.5+ matrix multiplication @

The @ operator calls the array’s __matmul__ method, not dot. This method is also present in the API as the function np.matmul. >>> a = np.random.rand(8,13,13) >>> b = np.random.rand(8,13,13) >>> np.matmul(a, b).shape (8, 13, 13) From the documentation: matmul differs from dot in two important ways. Multiplication by scalars is not allowed. Stacks of … Read more

What is the ‘@=’ symbol for in Python?

From the documentation: The @ (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator. The @ operator was introduced in Python 3.5. @= is matrix multiplication followed by assignment, as you would expect. They map to __matmul__, __rmatmul__ or __imatmul__ similar to how + and += map … Read more

Why is MATLAB so fast in matrix multiplication?

This kind of question is recurring and should be answered more clearly than “MATLAB uses highly optimized libraries” or “MATLAB uses the MKL” for once on Stack Overflow. History: Matrix multiplication (together with Matrix-vector, vector-vector multiplication and many of the matrix decompositions) is (are) the most important problems in linear algebra. Engineers have been solving … Read more