Search code examples
pythonnumpymatrix-multiplication

How come python do multiplication of two 4x1 matrices with same shape


I just realized that python does the multiplication of two matrices of 4x1, but as I know it is not possible two multiply a 4x1 matrix with another 4x1 matrix. I wrote the following code to test this:

import numpy as np

first_four_by_one = np.array([[1], [2], [3], [4]])
print(first_four_by_one.shape)

second_four_by_one = np.array([[4], [5], [6], [7]])
print(second_four_by_one.shape)

result = first_four_by_one * second_four_by_one
print(result.shape)
print(result)

and the result is as follows:

(4, 1)
(4, 1)
(4, 1)
[[ 4]
 [10]
 [18]
 [28]]

can anyone describe this please?


Solution

  • You are acually performing an element-wise matrix multiplication. To perform a matrix mutliplication, you should use the numpy function np.dot().

    For 2D matrices you can use also the @ operator which stand for np.matmul(). As written here, this operator can lead to side effects when working with higher dimension matrices (>2D)