Home > Mobile >  replace one with zero in identity matrix | Numpy |
replace one with zero in identity matrix | Numpy |

Time:11-13

I am learning Numpy. How do i get the expected output from identity matrix

identity matrix

1, 0, 0
0, 1, 0
0, 0, 1

Expected Output :

1, 0, 0
0, 0, 0
0, 0, 0

CodePudding user response:

Your question is unclear, however assuming you have a matrix of zeros with 1's on the diagonal and want to have all zeros but the first element:

a = np.array([[1,0,0],
              [0,1,0],
              [0,0,1]])
np.fill_diagonal(a, 0)
a[0,0] = 1

output:

array([[1., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])

CodePudding user response:

You can achieve using below method

Method 1 :

import numpy as np
arr=np.identity(3,dtype=int)
arr[1:,1:] = 0
arr

Output :

output 1

Method 2 :

import numpy as np
arr=np.identity(3,dtype=int)
arr[1:,:][0][1] = 0
arr[1:,:][1][-1] = 0
arr

Output :

output 1

Feel free to edit Incase any issue

  • Related