Hey There
Hey There

Reputation: 275

How to create an array by specifying diagonal values

I have an array like below:

  poles = numpy.array([[-1+1j], [-1-1j], [-2+3j], [-2-3j]])

Its shape is (4,1).

When I use the numpy.diag like below:

LA = numpy.diag(poles)

The output is [-1.+1.j] while I'm expecting to see a diagonal matrix. Can someone explain what is going on and what should be done to see a diagonal matrix? I also tried to change the shape to (1,4) but the result didn't change.

Upvotes: 0

Views: 1797

Answers (1)

busybear
busybear

Reputation: 10590

The function you are looking for is np.fill_diagonal. This will set the diagonal values of an array. You'll have to create the array first:

arr = np.zeros((4, 4), dtype=np.complex64))
np.fill_diagonal(arr, poles)

arr is now:

array([[-1.+1.j,  0.+0.j,  0.+0.j,  0.+0.j],
       [ 0.+0.j, -1.-1.j,  0.+0.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j, -2.+3.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j,  0.+0.j, -2.-3.j]], dtype=complex64)

np.diagonal, on the other hand, retrieves the values in the diagonal. Output of np.diagonal(arr) is:

array([-1.+1.j, -1.-1.j, -2.+3.j, -2.-3.j], dtype=complex64)

In your example, you are retrieving the diagonal of poles, which only has one value in the diagonal since one of the axes is only length 1.

Upvotes: 1

Related Questions