MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / _is_matrix_spd

Function _is_matrix_spd

linear_algebra/src/conjugate_gradient.py:12–45  ·  view source on GitHub ↗

Returns True if input matrix is symmetric positive definite. Returns False otherwise. For a matrix to be SPD, all eigenvalues must be positive. >>> import numpy as np >>> matrix = np.array([ ... [4.12401784, -5.01453636, -0.63865857], ... [-5.01453636, 12.33347422, -3.

(matrix: np.ndarray)

Source from the content-addressed store, hash-verified

10
11
12def _is_matrix_spd(matrix: np.ndarray) -> bool:
13 """
14 Returns True if input matrix is symmetric positive definite.
15 Returns False otherwise.
16
17 For a matrix to be SPD, all eigenvalues must be positive.
18
19 >>> import numpy as np
20 >>> matrix = np.array([
21 ... [4.12401784, -5.01453636, -0.63865857],
22 ... [-5.01453636, 12.33347422, -3.40493586],
23 ... [-0.63865857, -3.40493586, 5.78591885]])
24 >>> _is_matrix_spd(matrix)
25 True
26 >>> matrix = np.array([
27 ... [0.34634879, 1.96165514, 2.18277744],
28 ... [0.74074469, -1.19648894, -1.34223498],
29 ... [-0.7687067 , 0.06018373, -1.16315631]])
30 >>> _is_matrix_spd(matrix)
31 False
32 """
33 # Ensure matrix is square.
34 assert np.shape(matrix)[0] == np.shape(matrix)[1]
35
36 # If matrix not symmetric, exit right away.
37 if np.allclose(matrix, matrix.T) is False:
38 return False
39
40 # Get eigenvalues and eignevectors for a symmetric matrix.
41 eigen_values, _ = np.linalg.eigh(matrix)
42
43 # Check sign of all eigenvalues.
44 # np.all returns a value of type np.bool_
45 return bool(np.all(eigen_values > 0))
46
47
48def _create_spd_matrix(dimension: int) -> Any:

Callers 2

_create_spd_matrixFunction · 0.85
conjugate_gradientFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected