Challenge: Calculate the Matrix Multiplication Result
Tehtävä
Swipe to start coding
Your task is to write code that will multiply two matrices, A
and B
, using the dot product between two vectors.
- Specify the shape of the resulting matrix (number of rows and columns).
- Calculate the resulting matrix using the dot product between the corresponding rows of the first matrix and columns of the second matrix.
Ratkaisu
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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}')
Oliko kaikki selvää?
Kiitos palautteestasi!
Osio 2. Luku 2
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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}')
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme