Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I'm trying to multiply two matrices together using pure Python. Input (X1 is a 3x3 and Xt is a 3x2):

X1 = [[1.0016, 0.0, -16.0514], [0.0, 10000.0, -40000.0], [-16.0514, -40000.0, 160513.6437]] 

Xt = [(1.0, 1.0), (0.0, 0.25), (0.0, 0.0625)]

where Xt is the zip transpose of another matrix. Now here is the code:

def matrixmult (A, B): 

C = [[0 for row in range(len(A))] for col in

range(len(B[0]))] 

for i in range(len(A)): 

      for j in range(len(B[0])): 

for k in range(len(B)): 

C[i][j] += A[i][k]*B[k][j] 

return C

The error that python gives me is this:

IndexError: list index out of range.

Now I'm not sure if Xt is recognized as a matrix and is still a list object, but technically this should work.

1 Answer

0 votes
by (106k points)

You can use the below-mentioned code for matrix multiplication:-

def matmult(a,b):

zip_b = zip(*b)

zip_b = list(zip_b) 

return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a,

 col_b)) for col_b in zip_b] for row_a in a] 

x = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] 

y = [[1,2],[1,2],[3,4]] 

import numpy as np 

mx = np.matrix(x) 

my = np.matrix(y)

Related questions

0 votes
1 answer
asked Sep 24, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Mar 21, 2021 in Python by laddulakshana (16.4k points)
+1 vote
1 answer
asked Jul 31, 2019 in Python by Eresh Kumar (45.3k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers

500 comments

108k users

Browse Categories

...