Matrix Multiplication in python?

+1 vote
3 views

I want to multiply these two matrices using pure python. Input (M1 is 3*3 and Mt is a 3*2)

M1 =  [[1.0016, 0.0, -16.0514],
[0.0, 10000.0, -40000.0],
[-16.0514, -40000.0, 160513.6437]]
Mt =  [(1.0, 1.0),
(0.0, 0.25),
(0.0, 0.0625)]

Mt is zip transpose of another matrix. My code is :

def mtxmultply (X, Y):
Z = [[0 for row in range(len(X))] for col in range(len(Y[0]))]
for i in range(len(A)):
for j in range(len(Y[0])):
for k in range(len(Y)):
Z[i][j] += X[i][k]*Y[k][j]
return Z

IndexError: list index out of range. Not getting the surety if Mt is recognised as an matrix & is still a list object. But technically this should work.

1 Answer

+2 votes
by (10.9k points)
edited

The code should be like this for multiplication of two matrices in python-

# take a 3x3 matrix

C = [[1,1,1],

[1,1,1], [1,1,1]]

# take a 3x4 matrix

D= [[2,2,2, 2],

[2,2,2,2],

[2,2,2,2]]

R = [[0, 0, 0, 0],

[0, 0, 0, 0],

[0, 0, 0, 0]]

# iterating by row of A

for i in range(len(C)):

# iterating by column by D

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

# iterating by rows of D

for k in range(len(D)):

R[i][j] += C[i][k] * D[k][j]

for s in result:

print(s)

output-

[[6,6,6,6],

[6,6,6,6],

[6,6,6,6]]

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer