Home > Software design >  How to record all eigenvalues of a matrix in form of a diagonal matrix?
How to record all eigenvalues of a matrix in form of a diagonal matrix?

Time:09-22

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]]?

CodePudding user response:

Using numpy :

import numpy as np 
d = [d1,d2,d3]
diagonal = np.diag(d)

CodePudding user response:

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']
  • Related