Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Challenge: Calculate the Matrix Multiplication Result | Linear Algebra
Mathematics for Data Analysis and Modeling

book
Challenge: Calculate the Matrix Multiplication Result

Task
test

Swipe to show code editor

Your task is to write code that will multiply two matrices, A and B, using the dot product between two vectors.

  1. Specify the shape of the resulting matrix (number of rows and columns).
  2. Calculate the resulting matrix using the dot product between the corresponding rows of the first matrix and columns of the second matrix.

Solution

import numpy as np

# Define the matrices
A = np.array([[1, 2], [3, 4]]) # Matrix A with shape `(2, 2)`
B = np.array([[5, 6, -1, 0], [7, 8, 3, 1]]) # Matrix B with shape `(2, 4)`

# Calculate the matrix multiplication using dot product
rows = A.shape[0] # Number of rows in resulting matrix
cols = B.shape[1] # Number of cols in resulting matrix
C = np.zeros((rows, cols)) # Initialize the result matrix C

for i in range(rows):
for j in range(cols):
C[i, j] = np.dot(A[i, :], B[:, j]) # Dot product of row `A[i]` and column `B[j]`

# Print the result
print(C)
print(f'Shape of resulting matrix is: {C.shape}')

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 2
import numpy as np

# Define the matrices
A = np.array([[1, 2], [3, 4]]) # Matrix A with shape `(2, 2)`
B = np.array([[5, 6, -1, 0], [7, 8, 3, 1]]) # Matrix B with shape `(2, 4)`

# Calculate the matrix multiplication using dot product
rows = A.shape[___] # Number of rows in resulting matrix
cols = B.shape[___] # Number of cols in resulting matrix
C = np.zeros((rows, cols)) # Initialize the result matrix C

for i in range(rows):
for j in range(cols):
C[i, j] = np.___(A[i, :], B[:, j]) # Dot product of row `A[i]` and column `B[j]`

# Print the result
print(C)
print(f'Shape of resulting matrix is: {C.shape}')
toggle bottom row
some-alt