In the following code why same symbol * shows different behavior for matrices and arrays? Why doesn't it show element-wise multiplication in case of matrices?
a= np.arange(2*3).reshape(2,3)
print(a)
b= np.array([[0,0,0],[1,1,1]])
print(b)
c= a*b
print(c)
d=np.matrix([[1,2],[3,4]])
e= np.matrix([[0,0],[1,1]])
f= d*e
print("d: ",d,"e: ",e)
print(f)
Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays. Ndarrays apply almost all operations elemntwise.
The main advantage of numpy matrices is that they provide a convenient notation for matrix multiplication: if a and b are matrices, then a*b is their matrix product (not elementwise). The elementwise operation with np.matrix is obtained with np.multiply(a,b).
As of Python 3.5, NumPy supports infix matrix multiplication using the @ operator. Thus, np.matrix's * product is equivalent to np.array's @ product. In your code:
a= np.arange(2*2).reshape(2,2)
#> a = [[0 1]
# [2 3]]
b= np.array([[0,0],[1,1]])
#> b = [[0 0]
# [1 1]]
a@b
#>[[1 1]
# [3 3]]
a*b
#>[[0 0]
# [2 3]]
d=np.matrix([[0,1],[2,3]])
e= np.matrix([[0,0],[1,1]])
d*e # Equivalent to a@b
#> [[1 1]
# [3 3]]
np.multiply(d,e) # Equivalent to a*b
#> [[0 0]
# [2 3]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With