Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why same symbol shows element wise multiplication for array and matrix like multiplication for matrics?

Tags:

python

numpy

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)
like image 779
user10163680 Avatar asked Dec 08 '25 10:12

user10163680


1 Answers

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]]
like image 161
ibarrond Avatar answered Dec 09 '25 23:12

ibarrond