1 // Copyright ©2015 The Gonum Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
10 "gonum.org/v1/gonum/mat"
13 func ExampleCholesky() {
14 // Construct a symmetric positive definite matrix.
15 tmp := mat.NewDense(4, 4, []float64{
24 fmt.Printf("a = %0.4v\n", mat.Formatted(&a, mat.Prefix(" ")))
26 // Compute the cholesky factorization.
28 if ok := chol.Factorize(&a); !ok {
29 fmt.Println("a matrix is not positive semi-definite.")
32 // Find the determinant.
33 fmt.Printf("\nThe determinant of a is %0.4g\n\n", chol.Det())
35 // Use the factorization to solve the system of equations a * x = b.
36 b := mat.NewVecDense(4, []float64{1, 2, 3, 4})
38 if err := chol.SolveVec(&x, b); err != nil {
39 fmt.Println("Matrix is near singular: ", err)
41 fmt.Println("Solve a * x = b")
42 fmt.Printf("x = %0.4v\n", mat.Formatted(&x, mat.Prefix(" ")))
44 // Extract the factorization and check that it equals the original matrix.
49 fmt.Printf("L * L^T = %0.4v\n", mat.Formatted(&a, mat.Prefix(" ")))
52 // a = ⎡120 114 -4 -16⎤
57 // The determinant of a is 1.543e+06
65 // L * L^T = ⎡120 114 -4 -16⎤
71 func ExampleCholesky_SymRankOne() {
72 a := mat.NewSymDense(4, []float64{
78 fmt.Printf("A = %0.4v\n", mat.Formatted(a, mat.Prefix(" ")))
80 // Compute the Cholesky factorization.
82 if ok := chol.Factorize(a); !ok {
83 fmt.Println("matrix a is not positive definite.")
86 x := mat.NewVecDense(4, []float64{0, 0, 0, 1})
87 fmt.Printf("\nx = %0.4v\n", mat.Formatted(x, mat.Prefix(" ")))
89 // Rank-1 update the factorization.
90 chol.SymRankOne(&chol, 1, x)
91 // Rank-1 update the matrix a.
96 // Print the matrix that was updated directly.
97 fmt.Printf("\nA' = %0.4v\n", mat.Formatted(a, mat.Prefix(" ")))
98 // Print the matrix recovered from the factorization.
99 fmt.Printf("\nU'^T * U' = %0.4v\n", mat.Formatted(au, mat.Prefix(" ")))
117 // U'^T * U' = ⎡ 1 1 1 1⎤