Skip to content
Advertisement

np.diag not including 0s in the array

I have an expression that yields the following result:

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

I want to make a diagonal 2X2 matrix which has 0.5 and 0 on its diagonal. But when I use the following code:

np.diag(A)

A being the above array, I get the following result:

array([0.5])

Why does python not include the second element from A on the array and how can I include it?

Advertisement

Answer

x is 2d:

In [106]: x=np.array([[0.5],
     ...:    [0. ]])
In [107]: x
Out[107]: 
array([[0.5],
       [0. ]])
In [108]: x.shape
Out[108]: (2, 1)

Read diag docs – given a 2d array, it returns the diagonal:

In [109]: np.diag(x)
Out[109]: array([0.5])

Given a 1d array it returns a 2d array:

In [110]: np.diag(x[:,0])
Out[110]: 
array([[0.5, 0. ],
       [0. , 0. ]])
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement