Menu
Coddy logo textTech

Matrix Multiplications

Lesson 18 of 18 in Coddy's Numpy Fundamentals course.

Matrix multiplication is a series of dot products that produce a new matrix.

How it works?

Assume we have two matrices A with the shape of (3, 2) and B with the shape (2, 4). 

The multiplication of A and B will give a new matrix with the shape (3, 4).

The inner shapes of the matrices must match (in this case both A and B have 2 -> (3,2)(2,4)=(3,4))

multiplication of A*b is the 

  • dot product of Row 1 of A with Column 1 of B is the result of the element at [1, 1]
  • dot product of Row 1 of A with Column 2 of B is the result of the element at [1, 2]
  • ...
  • ...
  • dot product of Row 2 of A with Column 1 of B is the result of the element at [2, 1]
  • dot product of Row 2 of A with Column 2 of B is the result of the element at [2, 2]
  • ...
  • ...
  • etc.

Example:

Matrix A:

12
34
56

Matrix B:

78910
11121314

Result:

1*7 + 2*111*8 + 2*121*9 + 2*131*10 + 2*14
3*7 + 4*113*8 + 4*123*9 + 4*133*10 + 4*14
5*7 + 6*115*8 + 6*125*9 + 6*135*10 + 6*14

And after calculating:

29323538
65727986
101112123134

How to do it in numpy?

There are 3 ways to multiply matrices:

  • np.matmul(matrix1, matrix2)
  • matrix1.dot(matrix2)
  • A @ B
import numpy as np
A = np.array([[1, 2], [3, 4], [5, 6]])
B = np.array([[7, 8, 9, 10], [11, 12, 13, 14]])
np.matmul(A,B)

Output:

array([[ 29,  32,  35,  38],
       [ 65,  72,  79,  86],
       [101, 112, 123, 134]])
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Create a function called matrix_master that receives three python lists and return the matrix multiplication of the first two lists and perform a dot product of the result with the last list

Try it yourself

import numpy as np
def matrix_master(lst1, lst2, lst3):
    # complete

All lessons in Numpy Fundamentals