Home > Net >  How to change entire row/column to the same value in a matrix
How to change entire row/column to the same value in a matrix

Time:10-23

So I have this 3d array

x = np.zeros((9, 9))

Output:

[[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 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]]

and I want to change all of row x and column y into 1

Desired output:

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

I am doing this on a 3d array with Booleans instead of 0s and 1s but I assume that the answers would be the same.

CodePudding user response:

So first index is for the rows, and second index is for the columns. In your example, if you want to set row n to 1 just do the following:

x[n] = 1

I hope this helps.

CodePudding user response:

Use indexing with broadcasting:

x[n] = 1

# or
x[n,:] = 1
  • Related