0

I try to do the product of the elements of 2 different vectors and store the results in a matrix but I obtain the same value in each line of my matrix. Here is my code:

r=2    
a = [1,2]
b = [3,4,5]
rows, cols = (len(a),len(b))
C = [[0]*cols]*rows
print(C)
for i in range(len(a)):
  for j in range(len(b)):
    x=a[i]*b[j]/r
    C[i][j]=x 
print(C)

I obtain: C=[[3.0, 4.0, 5.0], [3.0, 4.0, 5.0]] while I would have like to obtain: C=[[1.5, 2.0, 2.5], [3.0, 4.0, 5.0]]

I do not understand why the both line of my matrix are fulfilled at each iteration on i.

Thank you in advance for your answer, Martin

Martin7
  • 93
  • 8

2 Answers2

0

The problem is that C = [[0]*cols]*rows refers to the same object in memory rows times. Because of this, whenever you change a row, you are referring all of them. There is different ways to initialize the matrix while avoiding this issue, e.g.: C = [[0]*cols for _ in range(rows)].

This problem has been discussed previously, see e.g. here.

Maybe not relevant for you yet, depending on whether this is an exercise, but in practice you would use matrix multiplications in numpy to perform these kind of tasks:

import numpy as np

a = np.array([[1,2]])
b = np.array([[3,4,5]])

a.T * b / 2

out: array([[1.5, 2. , 2.5],
            [3. , 4. , 5. ]])

mcsoini
  • 6,280
  • 2
  • 15
  • 38
0

The issue is the list being created is a pointer to each other inside. Making changes to one makes changes the other too.

You need to either use copy method or you can create the list in different method like so

r = 2
a = [1, 2]
b = [3, 4, 5]
rows, cols = (len(a), len(b))
C = [[0 for y in range(cols)] for x in range(rows)]
print(C)
for i in range(rows):
    for j in range(cols):
        x = a[i] * b[j] / r
        C[i][j] = x
print(C)

It is quick and easy to use a debugger to find these errors. Would suggest you try using the debugger to see how the values change in each iteration

shoaib30
  • 877
  • 11
  • 24