0

I used svd of a matrix A of size 64*64 in Python as follows.

U,D,V=svd(A)

Now, D is an array of all eigenvalues of A. How to rewrite all values in D as a diagonal matrix? For example, if D=[d1,d2,d3,d4], how to have

D_new=[[d1,0,0,0],[0,d2,0,0],[0,0,0,d3],[0,0,0,d4]]?
Hermi
  • 357
  • 1
  • 11
  • Does this answer your question? [How can I create a diagonal matrix with numpy?](https://stackoverflow.com/questions/58139494/how-can-i-create-a-diagonal-matrix-with-numpy) – Woodford Sep 21 '21 at 21:51

2 Answers2

3

Using numpy :

import numpy as np 
d = [d1,d2,d3]
diagonal = np.diag(d)
Ayyoub ESSADEQ
  • 776
  • 2
  • 14
  • Thanks! Can I ask how to compute the `diagonal^(-1/2)` in Python? – Hermi Sep 21 '21 at 21:46
  • @quasAliki Ask new questions in separate posts, not in comments. But if you do some simple searching, you'll find your [answer](https://stackoverflow.com/questions/5018552/how-to-raise-a-numpy-array-to-a-power-corresponding-to-repeated-matrix-multipl) – Woodford Sep 21 '21 at 21:50
  • @Woodford Well, this seems does not work for (-1/2). – Hermi Sep 21 '21 at 21:54
  • yes you can , do the following : `diagonal**(-1/2)` . But, it wouldn't work because you will have 1/0 which would be calculated as `inf` (infinity) – Ayyoub ESSADEQ Sep 21 '21 at 21:58
  • but , these is a solution : is `D = np.array(d)` then `D**(-1/2) ` then `diagonal = np.diag(D)` – Ayyoub ESSADEQ Sep 21 '21 at 22:01
1

create an empty vector of zero based on the length of your eigenvalues, then assign the position as you iterate over the list, appending to create a diagonal matrix

d=['d1','d2','d3','d4']
dnew=[]

for i,x in enumerate(d):
    vec=[0 for x in d]
    vec[i]=d[i]
    dnew.append(vec)

for x in dnew:
    print(x)  


['d1', 0, 0, 0]
[0, 'd2', 0, 0]
[0, 0, 'd3', 0]
[0, 0, 0, 'd4']
barker
  • 1,005
  • 18
  • 36