1

I have 3 2x2 Matrices, P1, P2, and P3, which are populated with randomly generated integers. I want to make sure that these matrices are positive definite (i.e. All eigenvalues are all greater than 0). My code is below.

P1 = np.random.randint(10, size=(m,n))
P2 = np.random.randint(10, size=(m,n))
P3 = np.random.randint(10, size=(m,n))
lambda1 = np.linalg.eigvals(P1)
lambda2 = np.linalg.eigvals(P2)
lambda3 = np.linalg.eigvals(P3)
for i in lambda1:  
  if (i <= 0): P1 = np.random.randint(10, size=(m,n))
for i in lambda2:
  if (i <= 0): P2 = np.random.randint(10, size=(m,n))
for i in lambda3:
  if (i <= 0): P3 = np.random.randint(10, size=(m,n))
print('Eigenvalue output to to verify that matrices are positive definite:\n')
print(u'\u03BB(P\u2081) = '  + str(np.linalg.eigvals(P1)))
print(u'\u03BB(P\u2082) = '  + str(np.linalg.eigvals(P2)))
print(u'\u03BB(P\u2083) = '  + str(np.linalg.eigvals(P3)))

Right now, the if statement will pretty much re-generate the matrix once or twice if the eigenvalues are not positive, but it will not verify that the eigenvalues are always positive. My first guess was to nest a while loop within the for loop, but I could not figure out a way to get that to work, and I'm unsure if that is the most efficient way.

2 Answers 2

2

This function creates an array with positive eigenvalues:

def create_arr_with_pos_ev(m,n):
    ev = np.array([-1,-1])
    while not all(ev>0):
        arr = np.random.randint(10, size=(m,n))
        ev = np.linalg.eigvals(arr)
    return arr, ev

First I define dummy eigenvalues, that are lower than 0. Then I create a new array and calculate its eigenvalues. If there is a negative eigenvalue (while not all(ev>0)), create a new one.

Sign up to request clarification or add additional context in comments.

Comments

0

As a supplement to the answer above, this can also be simplified a little further by taking out any input arguments to the function, and just defining the original matrix within the function:

def create_arr_with_pos_ev():
  arr = np.random.randint(10, size=(m,n))
  ev = np.linalg.eigvals(arr)
  while not all (ev >0):
    arr = np.random.randint(10, size=(m,n))
    ev = np.linalg.eigvals(arr)
  print('\nMatrix: \n' + str(arr) + '\nEigenvalues: \n',ev)
  return arr, ev

Print:

P1,eig1=create_arr_with_pos_ev()
P2,eig2=create_arr_with_pos_ev()
P3,eig3=create_arr_with_pos_ev()

Output:

Matrix: 
[[6 0]
 [3 7]]
Eigenvalues: 
 [7. 6.]

Matrix: 
[[9 3]
 [4 2]]
Eigenvalues: 
 [10.4244289  0.5755711]

Matrix: 
[[5 6]
 [3 8]]
Eigenvalues: 
 [ 2. 11.]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.