numpy.matmul()



The numpy.matmul() function returns the matrix product of two arrays. While it returns a normal product for 2-D arrays, if dimensions of either argument is >2, it is treated as a stack of matrices residing in the last two indexes and is broadcast accordingly.

On the other hand, if either argument is 1-D array, it is promoted to a matrix by appending a 1 to its dimension, which is removed after multiplication.

Example

# For 2-D array, it is matrix multiplication 
import numpy.matlib 
import numpy as np 

a = [[1,0],[0,1]] 
b = [[4,1],[2,2]] 
print np.matmul(a,b)

It will produce the following output −

[[4  1] 
 [2  2]] 

Example

# 2-D mixed with 1-D 
import numpy.matlib 
import numpy as np 

a = [[1,0],[0,1]] 
b = [1,2] 
print np.matmul(a,b) 
print np.matmul(b,a)

It will produce the following output −

[1  2] 
[1  2] 

Example

# one array having dimensions > 2 
import numpy.matlib 
import numpy as np 

a = np.arange(8).reshape(2,2,2) 
b = np.arange(4).reshape(2,2) 
print np.matmul(a,b)

It will produce the following output −

[[[2   3] 
   [6   11]] 
  [[10  19] 
   [14  27]]]
numpy_linear_algebra.htm
Advertisements