Insert elements in an empty matrix python using FOR loop

I am trying to do matrix multiplication. First i created an empty matrix C and then using for loop I am trying to do matrix multiplication and assign the results to matrix C.

# Matrix Multiplication
A = [[1, 2] , [3, 4]]
B = [[2, 3] , [2, 1]]
n = len(A) # No. of rows
j = len(A[0]) # No. of columns
C =[[]]
for i in range(len(A)):
    for j in range(len(A[0])):
        C[i][j] = 0
        for k in range(len(A)):
            C[i][j] = C[i][j] + A[i][k] * B[k][j]
print(C)

I am getting the error "list assignment index out of range".

Upvotes: 0

Views: 1014

Answers (1)

ComplicatedPhenomenon
ComplicatedPhenomenon

Reputation: 4199

You need to create C which has the number of rows same with A's and the number of columns same as B's.

# Matrix Multiplication
A = [[1, 2] , [3, 4]]
B = [[2, 3] , [2, 1]]
n = len(A) # No. of rows
j = len(A[0]) # No. of columns
C =[[0 for j in range(len(B[0]))] for i in range(len(A))]
for i in range(len(A)):
    for j in range(len(A[0])):
        for k in range(len(A)):
            C[i][j] = C[i][j] + A[i][k] * B[k][j]
print(C)

Output

[[6, 5], [14, 13]]

The matrix multiplication can be done via

import numpy as np
A = np.array([[1, 2] , [3, 4]])
B = np.array([[2, 3] , [2, 1]])
np.dot(A,B)

Upvotes: 2

Related Questions