How to Multiply 2D Matrices in Numpy?

Rate this post

Given two 2D arrays a and b. You can perform standard matrix multiplication with the operation np.matmul(a, b) if the array a has shape (x, y) and array be has shape (y, z) for some integers x, y, and z.

Problem Formulation: Given a two-dimensional NumPy array (=matrix) a with shape (x, y) and a two-dimensional array b with shape (y, z). In other words, the number of columns of a is the same as the number of rows of b. How to multiply a with b using standard matrix multiplication?

np.matmul() Example 2D Matrix Multiplication

Solution: Use the np.matmul(a, b) function that takes two NumPy arrays as input and returns the result of the multiplication of both arrays. The arrays must be compatible in shape.

Let’s dive into some examples!

Matrix Multiplication of a 2x2 with a 2x2 matrix

import numpy as np


a = np.array([[1, 1],
              [1, 0]])


b = np.array([[2, 0],
              [0, 2]])


c = np.matmul(a, b)

print(a.shape)
# (2, 2)

print(b.shape)
# (2, 2)

print(c)
'''
[[2 2]
 [2 0]]
'''

Matrix Multiplication of a 2x3 and a 3x2 Matrix

import numpy as np


a = np.array([[1, 1, 1],
              [1, 0, 1]])


b = np.array([[2, 0],
              [0, 2],
              [0, 0]])


c = np.matmul(a, b)

print(a.shape)
# (2, 3)

print(b.shape)
# (3, 2)

print(c)
'''
[[2 2]
 [2 0]]
'''

NumPy Puzzle: Matrix Multiplication

import numpy as np

# graphics data
a = [[1, 1],
     [1, 0]]

# stretch vectors
b = [[2, 0],
     [0, 2]]
c = np.matmul(a, b)

print(c[0, 1])

What is the output of this puzzle?

Numpy is a popular Python library for data science focusing on arrays, vectors, and matrices.

This puzzle shows an important application domain of matrix multiplication: Computer Graphics.

We create two matrices a and b. The first matrix a is the data matrix (e.g. consisting of two column vectors (1,1) and (1,0)). The second matrix b is the transformation matrix that transforms the input data. In our setting, the transformation matrix simply stretches the column vectors.

More precisely, the two column vectors (1,1) and (1,0) are stretched by factor 2 to (2,2) and (2,0). The resulting matrix is therefore [[2,2],[2,0]]. We access the first row and second column.


Are you a master coder?
Test your skills now!

Related Video

Matrix multiplication (part 1)