forked from skelterjohn/go.matrix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sparse_basic.go
105 lines (93 loc) · 2 KB
/
sparse_basic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Copyright 2009 The GoMatrix Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package matrix
import "math"
/*
Swap two rows in this matrix.
*/
func (A *SparseMatrix) SwapRows(r1, r2 int) {
js := map[int]bool{}
for index := range A.elements {
i, j := A.GetRowColIndex(index)
if i == r1 || i == r2 {
js[j] = true
}
}
for j := range js {
tmp := A.Get(r1, j)
A.Set(r1, j, A.Get(r2, j))
A.Set(r2, j, tmp)
}
}
/*
Scale a row by a scalar.
*/
func (A *SparseMatrix) ScaleRow(r int, f float64) {
for index, value := range A.elements {
i, j := A.GetRowColIndex(index)
if i == r {
A.Set(i, j, value*f)
}
}
}
/*
Add a multiple of row rs to row rd.
*/
func (A *SparseMatrix) ScaleAddRow(rd, rs int, f float64) {
for index, value := range A.elements {
i, j := A.GetRowColIndex(index)
if i == rs {
A.Set(rd, j, A.Get(rd, j)+value*f)
}
}
}
func (A *SparseMatrix) Symmetric() bool {
for index, value := range A.elements {
i, j := A.GetRowColIndex(index)
if i != j && value != A.Get(j, i) {
return false
}
}
return true
}
func (A *SparseMatrix) Transpose() *SparseMatrix {
B := ZerosSparse(A.cols, A.rows)
for index, value := range A.elements {
i, j := A.GetRowColIndex(index)
B.Set(j, i, value)
}
return B
}
func (A *SparseMatrix) Det() float64 {
//TODO: obviously this is a horrible way to do it
return A.DenseMatrix().Det()
}
func (A *SparseMatrix) Trace() (res float64) {
for index, value := range A.elements {
i, j := A.GetRowColIndex(index)
if i == j {
res += value
}
}
return
}
func (A *SparseMatrix) OneNorm() (res float64) {
for _, value := range A.elements {
res += math.Abs(value)
}
return
}
func (A *SparseMatrix) TwoNorm() float64 {
var sum float64 = 0
for _, value := range A.elements {
sum += value * value
}
return math.Sqrt(sum)
}
func (A *SparseMatrix) InfinityNorm() (res float64) {
for _, value := range A.elements {
res = max(res, math.Abs(value))
}
return
}