简体   繁体   中英

How to use assert with condition to check on every element in a matrix in Python?

I am checking if a matrix is positive definite by computing the eigenvalues of the matrix.

matrix = np.array([[0.0070123 , 0.00578589, 0.01867008, 0.00351521, 0.00151787],
       [0.00578589, 0.00590836, 0.01657745, 0.00304733, 0.0013278 ],
       [0.01867008, 0.01657745, 0.0555186 , 0.01004483, 0.00439243],
       [0.00351521, 0.00304733, 0.01004483, 0.00270608, 0.00080408],
       [0.00151787, 0.0013278 , 0.00439243, 0.00080408, 0.00084371]])

eigenvalues = np.linalg.eievals(matrix)

Out[20]: array([0.06913077, 0.0004869 , 0.00057456, 0.0009318 , 0.00086503])

Apparently, this matrix is positive definite since all eigenvalues are greater than 0. Now I wish to use assert to make sure this matrix always stays positive definite, that is, all eigenvalues are greater than 0, since I will put this code into a function. I know np.where can be used to check on condition and return the desired output/elements, but I wonder if I can apply this with assert ? Or is there any better way I can compute this?

You can do this using np.all which returns True if all elements of an array are True and returns False otherwise. More details in thedocs :

The following code should achieve what you want

assert np.all(eigenvalues > 0)

If you are trying to raise an error, you can use np.any which returns True if at least one element of the array is True

if np.any(eigenvalues <= 0):
    raise YourError

Something like this could do the trick:

booleans = np.unique(np.any(eigenvalues > 0))
assert len(booleans) == 1 and booleans[0]

You'll first check if there is eigenvalues below zero, which will return a boolean array which you check the unique values of. If you have only True values you can check with the .unique() function to make sure that you have only one value in the array and that it's True so that you do not have a full negative eigenvalue matrix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM