Setting diagonal of a matrix to zero

42 views Asked by At
m = [[[math.inf] * 10] for i in range(10)]

for i in range(len(m)):
    for j in range(len(m)):
        if(i == j):
            m[i][i] = 0

I try to insert zero And I used the debugger to watch the process go. Instead of changing it to

[[[0,inf,inf,inf,inf,inf,inf,inf,inf,inf],[......],[.......]]]

It changes it to

[[0], [[inf,inf,inf,inf....],[inf,inf,....]]

Which then causes an index out of bound error because it just reduced a 10x10 matrix to the top row being zero, as opposed to inf,inf,inf,inf,inf,inf,inf,inf,inf,inf.

Where my goal is to set a 10x10 matrix's diagonal to all zeros.

I tried to use:

m = [[[math.inf] * 10] for i in range(10)]
1

There are 1 answers

0
YoussefNim On

As @Christopher-Renauro pointed out, you currently have a list of length 10.

Setting the diagonal of a matrix to zeros can be easily done using Numpy.

  • convert your list to a numpy array of 10x10 shape : new_m = np.array(m).reshape(10,10)
  • use fill_diagonal() : fill_diagonal(new_m, val=0)