Dot vs Element-wise multiplication

Dot Multiplication

Properties

  • It is performed via numpy.dot or using the @ operator.
  • It represents the traditional matrix multiplication.
  • Involves summing the products of corresponding elements in rows and columns.
  • Output shape depends on the input shapes:
  • For matrices A (m x n) and B (n x p), the output is (m x p).
  • For vectors, it produces a scalar (single value).

Example

import numpy as np
a = np.array([[1, 2], [3, 4]]) #  [[1 2]
                              #   [3 4]]

b = np.array([[5, 6], [7, 8]]) #  [[5 6]
                              #   [7 8]]

result = np.dot(a, b)  # Or result = a @ b
print(result)  # Output: [[19 22]
             #           [43 50]]

Element-wise multiplication

Properties

  • It is performed using numpy.multiply or using the * operator.
  • It implies multiplying corresponding elements of arrays directly.
  • Output shape matches the input shapes (if compatible).
  • Broadcasting rules apply for different-shaped arrays.

Example

a = np.array([1, 2, 3])
b = np.array([4, 5, 6]) 
result = np.multiply(a, b) # Or result = a * b
print(result) # Output: [ 4 10 18]