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:
| 1 | 2 |
| 3 | 4 |
| 5 | 6 |
Matrix B:
| 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 |
Result:
| 1*7 + 2*11 | 1*8 + 2*12 | 1*9 + 2*13 | 1*10 + 2*14 |
| 3*7 + 4*11 | 3*8 + 4*12 | 3*9 + 4*13 | 3*10 + 4*14 |
| 5*7 + 6*11 | 5*8 + 6*12 | 5*9 + 6*13 | 5*10 + 6*14 |
And after calculating:
| 29 | 32 | 35 | 38 |
| 65 | 72 | 79 | 86 |
| 101 | 112 | 123 | 134 |
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]])This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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
2N-Dimensional Array Creation
Higher DimensionUnderstanding ShapesPopulate with Fixed ValuesNumpy TypesRangeReshape