Home > Software design >  How to change a specific element in a matrix to match another matrix?
How to change a specific element in a matrix to match another matrix?

Time:11-11

I am writing a program that involves me to create a matrix 'B' edited from another matrix 'A'. Both the matrix have the same size and I simply want that for every position where matrix 'A' contains a 1, matrix 'B' also contains a 1 in that position. For example:

if __name__ == '__main__':
    mat_A = [[0, 0, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 0, 0]]
    R = len(mat_A)
    C = len(mat_A[1])
    mat_B = [[0]*C]*R                   #Initialise matrix B to be the same size as A

    for i in range (R):
        for j in range (C):
            if mat_A[i][j] == 1:
                mat_B[i][j] = 1
            print(mat_B)

However, in this case, it prints me an output like such:

[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]

Process finished with exit code 0

This tells me that the code is finding an instance where mat_A[i][j] = 1 and then changing the entire mat_B together. Shouldn't it only affect the specific position in 'B' rather than all?

Thank you for your help.

p.s. The above is only a very simple example I wrote to try and debug. There are multiple complex steps in the if loop.

CodePudding user response:

The line

mat_B = [[0]*C]*R

creates a list of length R where each element is the same list consisting of zeros. If you change one of the sublists of mat_B, you change them all, since they are all the same list. You can fix this, for example, as follows:

mat_B =  [[0]*C for i in range(R)]

After that, your code should work fine.

As a side note, it is easier to accomplish such operations using numpy arrays:

import numpy as np 

mat_A = np.array([[1, 2, 3], [0, 1, 7], [3, 1, 0], [0, 1, 0], [0, 2, 4]]) 
mat_B = np.zeros_like(mat_A)
mat_B[mat_A == 1] = 1
  • Related