0

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".

3
  • Why are you not using numpy for actual matrix processing? Only lists are used in your posted example. Commented Sep 1, 2019 at 2:53
  • I am studying Algorithms. So I am trying to get my concept right by trying to code without the inbuilt functions/libraries. Commented Sep 1, 2019 at 3:05
  • Python is not one of those languages that creates a new list element by simple assignment. Commented Sep 1, 2019 at 5:12

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.