-1

I'm trying to create a function that adds two 3x3 matrices together, but my output doesn't give me the desired values.

I added the print-function in the nested for-loops to see how the code was working:

  sum_of_a_b = [[0] * 3] * 3
  
  for i in range(0, 3):
    for j in range(0, 3):
     sum_of_a_b[i][j] = matrix_a[i][j] + matrix_b[i][j]
     print(answer)

Output:
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[1, 9, 0], [1, 9, 0], [1, 9, 0]]
[[1, 9, 5], [1, 9, 5], [1, 9, 5]]
[[1, 9, 5], [1, 9, 5], [1, 9, 5]]
[[1, -2, 5], [1, -2, 5], [1, -2, 5]]
[[1, -2, 5], [1, -2, 5], [1, -2, 5]]
[[6, -2, 5], [6, -2, 5], [6, -2, 5]]
[[6, 7, 5], [6, 7, 5], [6, 7, 5]]
[[6, 7, 8], [6, 7, 8], [6, 7, 8]]
[[6, 7, 8], [6, 7, 8], [6, 7, 8]]

Why does my code return the sum of a+b(i,j) on every list rather than the specific element in each list?

  • 2
    Your code doesn't "return" anything at all, it prints `answer` on every loop iteration, which is some value that is unknown to us (you've omitted it from your example). – Alexander Oct 14 '21 at 13:19
  • It does `for j in range(0, 3)` for _every iteration of the outer loop_. If you want to pair elements up with each other, then do `for i, j in zip(range(0, 3), range(0, 3))` – Green Cloak Guy Oct 14 '21 at 13:19
  • 3
    Also since you're using `* 3` on a list you get 3 references to the same list. Modifying one will modify all the others. This is not what you want. – Omer Tuchfeld Oct 14 '21 at 13:21
  • See https://stackoverflow.com/questions/44915324/why-does-creating-a-list-of-lists-produce-unexpected-behavior why `sum_of_a_b = [[0] * 3] * 3` is wrong. – Michael Butscher Oct 14 '21 at 13:22
  • 2
    Why not use NumPy for matrix work? – Travis Oct 14 '21 at 13:24
  • I'm learning to create the codes without the use of NumPy to improve my coding skills –  Oct 14 '21 at 13:31
  • 2
    @Travis - numpy is great, but it's even better for language understanding if beginners learn how to do basic things in the language. The answer to this question for instance will teach the coder why this is bad: `sum_of_a_b = [[0] * 3] * 3` – DarrylG Oct 14 '21 at 13:31

1 Answers1

1

This function will do what you want:

def sum_matrices(matrix_a, matrix_b):
  sum_of_a_b = [0 for i in range(3)] for i in range(3)]
  
  for i in range(0, 3):
    for j in range(0, 3):
     sum_of_a_b[i][j] = matrix_a[i][j] + matrix_b[i][j]
  return sum_of_a_b

EDIT:

Your mistakes were:

  1. What you wrote was a script and not a function and so it didn't anything.
  2. [[0] * 3] * 3 generates a list [0], duplicates it, and then duplicated again but this time by reference and so every row has the same pointer and once you change a certain value its whole column is changed the same way.
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459