Search code examples
pythonmatrixvectoroperation

Python product of the elements of 2 vectors into a matrix


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


Solution

  • 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. ]])