I have an expression that yields the following result:
JavaScript
x
3
1
array([[0.5],
2
[0. ]])
3
I want to make a diagonal 2X2 matrix which has 0.5 and 0 on its diagonal. But when I use the following code:
JavaScript
1
2
1
np.diag(A)
2
A being the above array, I get the following result:
JavaScript
1
2
1
array([0.5])
2
Why does python not include the second element from A on the array and how can I include it?
Advertisement
Answer
x
is 2d:
JavaScript
1
9
1
In [106]: x=np.array([[0.5],
2
0. ]]) : [
3
In [107]: x
4
Out[107]:
5
array([[0.5],
6
[0. ]])
7
In [108]: x.shape
8
Out[108]: (2, 1)
9
Read diag
docs – given a 2d array, it returns the diagonal:
JavaScript
1
3
1
In [109]: np.diag(x)
2
Out[109]: array([0.5])
3
Given a 1d array it returns a 2d array:
JavaScript
1
5
1
In [110]: np.diag(x[:,0])
2
Out[110]:
3
array([[0.5, 0. ],
4
[0. , 0. ]])
5