Python Forum

Full Version: Matrix Multiplication Issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have written the code given below in two different cases
Case I
a = [[1,2,3],[4,5,6],[7,8,9]]
b = a
i = 0
j = 0
while (i<3):
    while (j<3):
        b[j][i] = a[i][j]
        j = j + 1
    j = 0
    i = i + 1
print(a)
print(b)
The result is
Output:
[[1, 2, 3], [2, 5, 6], [3, 6, 9]] [[1, 2, 3], [2, 5, 6], [3, 6, 9]]
Case II
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[1,2,3],[4,5,6],[7,8,9]]
i = 0
j = 0
while (i<3):
    while (j<3):
        b[j][i] = a[i][j]
        j = j + 1
    j = 0
    i = i + 1
print(a)
print(b)
The result is
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
In Case I, the values in the matrix is changing and the result is not correct.
In Case II, the result is correct but the way in which matrix b is defined is different.

Any reasons for this change in the result and kindly mention the error in the code in Case I.
In case 1, a and b are the same list instance, you could as well do a[j][i] = a[i][j].

Here is another way to transpose double lists
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> b = [list(x) for x in zip(*a)]
>>> b
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]