Home > Blockchain >  How to convert diameter of matrix to zero in python?
How to convert diameter of matrix to zero in python?

Time:10-23

I have a matrix and I want to convert diameter value to zero in python. can you help me?

Matrix:

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

CodePudding user response:

assuming you meant diagonal, iterate over the list with enumerate, then iterate over the sublist, and check if the indexes are equal (that means you're on the diagonal), and assign zero, else the current value.

mydata = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]

out=[]
for i,l in enumerate(mydata):
    n=[]
    for j,v in enumerate(l):
        if i==j:
            n.append(0)
        else:
            n.append(v)
    out.append(n)
for x in out:
    print(x)  
[0, 2, 3, 4]
[5, 0, 7, 8]   
[9, 10, 0, 12] 
[13, 14, 15, 0]
  • Related