1

I have a numpy 2d array:

import numpy as np
A=np.array([[1, 2, 3, 4],
            [5, 6, 7, 8],
            [9, 10, 11, 12],
            [13, 14, 15, 16]])
print (A)

I would like to replace the diagonal elements with a = np.array([0,2,15,20]). That is the desired output should be:

A=[[0, 2, 3, 4],
    [5, 2, 7, 8],
    [9, 10, 15, 12],
    [13, 14, 15, 20]]

I tried with the following code:

import numpy as np
A=np.array([[1, 2, 3, 4],
            [5, 6, 7, 8],
            [9, 10, 11, 12],
            [13, 14, 15, 16]])
a = np.array([0,2,15,20])
print(np.fill_diagonal(A, a))

But it resulted in None

1
  • 4
    The np.fill_diagonal function modifies the input array in-place, it does not return a value. Try print(A) afterwards to see result. Commented Mar 31, 2022 at 22:50

2 Answers 2

2

As an alternative method if a be the main array and b the modified values array:

a_mod = a.ravel()
a_mod[::a.shape[0]+1] = b
result = a_mod.reshape(a.shape)

It can handle where the other diagonals of a matrix (instead the main diagonal) is of interest, by some modification. np.fill_diagonal works on the main diagonal.

Sign up to request clarification or add additional context in comments.

Comments

1

try this

A[np.arange(4), np.arange(4)] = a

array([[ 0,  2,  3,  4],
       [ 5,  2,  7,  8],
       [ 9, 10, 15, 12],
       [13, 14, 15, 20]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.