Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Matrix Multiplication Issue
#1
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.
Reply
#2
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]]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Check if two matrix are equal and of not add the matrix to the list quest 3 778 Jul-10-2023, 02:41 AM
Last Post: deanhystad
  matrix multiplication term by term karolina 1 801 Dec-10-2022, 10:11 AM
Last Post: Gribouillis
  Multiplication Table code alexsendlegames100 3 1,317 Jun-06-2022, 09:45 AM
Last Post: Gribouillis
  Try to solve GTG multiplication table problem. Frankduc 6 1,937 Jan-18-2022, 08:26 PM
Last Post: Frankduc
  Need help with my Python code (Multiplication) NeedHelpPython 2 1,635 Oct-04-2021, 12:09 PM
Last Post: Pedroski55
  How to multiply a matrix with herself, until the zero matrix results peanutbutterandjelly 3 3,304 May-03-2021, 06:30 AM
Last Post: Gribouillis
  List conversion and multiplication johnkyp 5 3,105 Jan-02-2020, 08:20 AM
Last Post: perfringo
  Multiplication between a list and a variable doug2019 2 2,123 Oct-08-2019, 04:10 AM
Last Post: doug2019
  Multiplication Table number margins CJ707 4 2,366 Sep-18-2019, 02:16 PM
Last Post: CJ707
  multiplication by successive addition Zebrol 1 3,471 Sep-14-2019, 05:37 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020