turn random matrices to positive semidefinite

Viewed 102

I have a problem when i generate random matrices and turn them into positive semidefinite. If we take a random matrix Q and then multiply it with its transpose then the outcome should be positive semidefinite ( no negative eigenvalues) However when i print some random eigenvalues i see that i have negative ones. Does my code has something wrong? Also I want to save the max values of the eigenvalues into a vector. My Q random matrices are integers and the eigenvalues from what i ve seen are real numbers and the complex part is always 0. However i get a warning as well. Let me show you my code first

#here i create a random torch with N matrices of n by n size
Q = torch.randint(0, 10, size=(N, n, n))

#here i initialize my vector for the max eigenvalues
max=np.zeros(N)

#here i create a loop where i multiply each Q matrix in my torch with its transpose
for i in range(0,N):
    Q[i] = Q[i]*Q[i].t()
    #here i find my eigenvalues and save the max into my vector max
    val,vec=lg.eig(Q[i])
    max[i]= np.amax(val)

The warning i get is

ComplexWarning: Casting complex values to real discards the imaginary part

and my eigenvalues i print them from the console with the command

lg.eig(Q[0])
However i see for example
(array([120.20198423+0.j,  -1.93985888+0.j,  34.73787466+0.j])

Which has a negative value
1 Answers

Your example is a random integer matrix, but your warning message implies Q contains complex values.

As such, in order to create a positive semidefinite matrix you must multiply Q by its conjugate transpose torch.conj(Q).t() (this is equivalent to the transpose across the reals).

Also, you are computing the dot product by using *, for matrix multiplication use @, torch.mm or torch.matmul.

Related