0

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?

Farid
  • 5
  • 2
  • 1
    This is an element-wise multiplication. The mathematical matrix multiplication got its own operator `@` in newer Python versions. – Michael Butscher Oct 29 '20 at 17:39
  • Well, this is not matrix multiplication. It is just multiplying all members of the two arrays. – zvone Oct 29 '20 at 17:40

1 Answers1

2

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)

Antoine Dubuis
  • 4,974
  • 1
  • 15
  • 29