189k views
1 vote
Write your own code to perform matrix multiplication. Recall that to multiply two matrices, the inner dimensions must be the same.

[A] _mn[B] _np = [C] _mp
Every element in the resulting C matrix is obtained by:
C_jj= Σaᵢₖbᵢₖ
The sum is from k=1 to n. So three nested loops are required. Please remember to comment your code.

1 Answer

5 votes

Final answer:

To perform matrix multiplication, follow a specific algorithm: check compatibility, initialize matrix C, use three nested loops, calculate each element of C, and return C. Here's an example code in Python that performs matrix multiplication.

Step-by-step explanation:

In order to perform matrix multiplication, we need to follow a specific algorithm:

  1. First, we check if the dimensions of the matrices are compatible for multiplication. The number of columns in the first matrix (n) should be equal to the number of rows in the second matrix (p).
  2. We initialize an empty matrix C with dimensions m x p, where m is the number of rows in the first matrix and p is the number of columns in the second matrix.
  3. We use three nested loops to iterate through the elements of the matrices and calculate the elements of C. The outermost loop iterates over the rows of the first matrix, the middle loop iterates over the columns of the second matrix, and the innermost loop iterates over the columns of the first matrix or the rows of the second matrix.
  4. For each element C[j][j] in the resulting matrix C, we calculate the sum of the products of corresponding elements from the first matrix (A) and the second matrix (B). The formula for calculating C[j][j] is Σa[i][k]b[k][j], where the sum is from k=1 to n. We store the result in C[j][j].
  5. Finally, we return the resulting matrix C as the product of the two input matrices.

Here is an example code in Python that performs matrix multiplication:

def matrix_multiplication(A, B):
m = len(A)
n = len(A[0])
p = len(B[0])
C = [[0 for _ in range(p)] for _ in range(m)]
for i in range(m):
for j in range(p):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
return C

You can call this function by passing two matrices A and B as input:

A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
C = matrix_multiplication(A, B)
print(C) # Output: [[19, 22], [43, 50]]