Singular value decomposition: Difference between revisions
Content added Content deleted
m (Modify Python's format) |
(Added Go) |
||
Line 49: | Line 49: | ||
2. The algorithm should be applicable for general case(<math>m\times n</math>). |
2. The algorithm should be applicable for general case(<math>m\times n</math>). |
||
=={{header|Go}}== |
|||
{{libheader|gonum}} |
|||
The SVD.Factorize method can decompose any m x n matrix though the example here is for a 2 x 2 matrix. |
|||
<syntaxhighlight lang="go"><package main |
|||
import ( |
|||
"fmt" |
|||
"gonum.org/v1/gonum/mat" |
|||
"log" |
|||
) |
|||
func matPrint(m mat.Matrix) { |
|||
fa := mat.Formatted(m, mat.Prefix(""), mat.Squeeze()) |
|||
fmt.Printf("%13.10f\n", fa) |
|||
} |
|||
func main() { |
|||
var svd mat.SVD |
|||
a := mat.NewDense(2, 2, []float64{3, 0, 4, 5}) |
|||
ok := svd.Factorize(a, mat.SVDFull) |
|||
if !ok { |
|||
log.Fatal("Something went wrong!") |
|||
} |
|||
u := mat.NewDense(2, 2, nil) |
|||
svd.UTo(u) |
|||
fmt.Println("U:") |
|||
matPrint(u) |
|||
values := svd.Values(nil) |
|||
sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]}) |
|||
fmt.Println("\nΣ:") |
|||
matPrint(sigma) |
|||
vt := mat.NewDense(2, 2, nil) |
|||
svd.VTo(vt) |
|||
fmt.Println("\nVT:") |
|||
matPrint(vt) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
U: |
|||
⎡-0.3162277660 -0.9486832981⎤ |
|||
⎣-0.9486832981 0.3162277660⎦ |
|||
Σ: |
|||
⎡6.7082039325 0.0000000000⎤ |
|||
⎣0.0000000000 2.2360679775⎦ |
|||
VT: |
|||
⎡-0.7071067812 -0.7071067812⎤ |
|||
⎣-0.7071067812 0.7071067812⎦ |
|||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |