bbm
bbm

Reputation: 43

Matrix Multiplication in Python Language

I'm trying to do a Matrix multiplication using nested while loops for the given hard coded matrices...

The correct answer for this should be [[6,12], [15,30], [24,48]]

but the output of my code is [[6,12], [6,12], [6,12]]

what should I do?

a=[[1,2,3],[4,5,6],[7,8,9]]
b=[[1,2],[1,2],[1,2]]
c=[]

cola=len(a)
rowa=len(a[0])
colb=len(b)
rowb=len(b[0])
r,s,t,u,sum = 0,0,0,0,0

c=[([0]*rowb)]*cola

print c


while s<cola:
    while u<rowb:  
        while t<colb:
            d=a[s][t]*b[t][r]
            sum+=d
            t+=1

        c[s][r]=sum
        sum=0
        u+=1
        t=0
        r+=1

    r=0    
    s+=1

print c

Upvotes: 1

Views: 508

Answers (2)

zebo zhuang
zebo zhuang

Reputation: 636

#!/usr/bin/env python
#-*- coding: utf-8 -*-

matrixA = [[1,2,3],[4,5,6],[7,8,9]]
matrixB = [[1,2],[1,2],[1,2]]
result = []

for row in range(len(matrixA)):
    rowResult = []
    for column in range(len(matrixB[0])):
        s = 0
        l = len(matrixA[row])
        for i in range(l):
            s += matrixA[row][i]*matrixB[i][column]
        rowResult.append(s)
    result.append(rowResult)

print result

I try this, it is correct.

Upvotes: 0

Anand S Kumar
Anand S Kumar

Reputation: 90859

When you do -

c=[([0]*rowb)]*cola

You are just copying the inner list cola times, this is shallow copying, hence each inner list is a reference to the same object , hence when you change an element inside one of the inner lists, it affects all of the inner lists. Instead of that, try using list comprehension to create the c list.

Example -

c = [[0 for _ in range(rowb)] for _ in range(cola)]

Also, another small issue in your logic, you are using r to denote the elements from b , but in the while loop you are checking against - u , you should check against r . Example -

while s<cola:
    while r<rowb: 

Upvotes: 1

Related Questions