Multiplying Arrays of Different Dimensions

In NumPy, you can simply use a few functions, as mentioned in this article, to perform matrix multiplication between two arrays. However, before you can multiply the two arrays in question, you need to ensure that their shapes are compatible with matrix multiplication. If they’re not compatible to be multiplied, then you’ve to make them compatible to be multiplied. In this article, we will explore how to multiply arrays of different dimensions using three different NumPy methods. In the methods below, we will have two arrays A with dimensions (5, 5, 3) and array B with dimensions (5, 5).

1. Using "Broadcasting":

  • Broadcasting is the process of making arrays with different shapes compatible with arithmetic operations.
  • Here, we first import the NumPy library and assign it the alias np. Then, the code creates two random NumPy arrays called a and b.
  • It then uses broadcasting to multiply a and b along the last axis, resulting in a new array c with dimensions (5, 5, 3).
  • The resulting shape of c indicates that the last axis of b was broadcasted to match the third axis of a. The commented-out line can be uncommented to print the resulting array c.

2. Using "np.reshape()":

  • In this technique, we first import the NumPy library and assign it the alias np. Then, the code creates two random NumPy arrays called a and b.
  • It then reshapes b to have the same dimensions as a using b.reshape((5,5,1)).
  • It then multiplies a and b_reshaped along the last axis, resulting in a new array c with dimensions (5,5,3).
  • The resulting shape of c indicates that the last axis of b was reshaped to match the third axis of a. The commented-out line can be uncommented to print the resulting array c.

3. Using Einstein Summation "(np.einsum)":

  • Here, we first import the NumPy library and assign it the alias np. Then, the code creates two random NumPy arrays called a and b.
  • It then uses Einstein summation to multiply a and b along the last axis, resulting in a new array c with dimensions (5,5,3).
  • The resulting shape of c indicates that the last axis of b was used to multiply the last axis of a. The commented-out line can be uncommented to print the resulting array c.