pythonnumpymatrix

Is there a way to MODIFY the diagonals (not just the centeral diagonal) of a matrix A by using just np.diag()?


Is there a way to MODIFY the diagonals (not just the centeral diagonal) of a matrix A by using just np.diag()? (so not using np.fill_diag() ). Im not sure how to do a diagonal above the center diagonal for example. I can access the other diagonals but not able to edit them using just np.diag(). Any methods?

I tried using np.diag() and could read the other diagonals but not change them. Ulitmatly i had to use this super skethcy for loop to change them manually. np.fill_diag() worked for just the main center diagonal but not the others. So help would be nice!


Solution

  • You can just use fill_diagonal with a slice of your array to shift the diagonal:

    import numpy as np
    
    M, N = 4, 5
    
    rng = np.random.default_rng(0)
    
    A = rng.random((M, N))
    print(A)
    
    np.fill_diagonal(A[:, 1:], 0) # Shifts diagonal 1 `horizontally`
    print(A)
    

    Output:

    [[0.63696169 0.26978671 0.04097352 0.01652764 0.81327024]
     [0.91275558 0.60663578 0.72949656 0.54362499 0.93507242]
     [0.81585355 0.0027385  0.85740428 0.03358558 0.72965545]
     [0.17565562 0.86317892 0.54146122 0.29971189 0.42268722]]
    [[0.63696169 0.         0.04097352 0.01652764 0.81327024]
     [0.91275558 0.60663578 0.         0.54362499 0.93507242]
     [0.81585355 0.0027385  0.85740428 0.         0.72965545]
     [0.17565562 0.86317892 0.54146122 0.29971189 0.        ]]