-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix.go
66 lines (53 loc) · 1.57 KB
/
matrix.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
package convnet
// various functions for matrix operations
// trivial maths performance, they could be improved!
import (
"errors"
)
// Matrix basic matrix struct (float64)
type Matrix struct {
content [][]float64
}
// Multiply returns the result matrix calculation from matrix * matrix2
// or error if the shapes are not correct
func (matrix *Matrix) Multiply(matrix2 *Matrix) (*Matrix, error) {
if len(matrix.content[1]) != len(matrix2.content) {
return nil, errors.New("matrix cols are not equals to matrix2 rows")
}
result := &Matrix{
content: make([][]float64, len(matrix.content[1])),
}
for i := 0; i < len(matrix.content); i++ {
result.content[i] = make([]float64, len(matrix2.content[0]))
for j := 0; j < len(matrix2.content[0]); j++ {
for k := 0; k < len(matrix2.content); k++ {
result.content[i][j] += matrix.content[i][k] * matrix2.content[k][j]
}
}
}
return result, nil
}
// Flattening flat a matrix NxM to a matrix (1, N+M)
func (matrix *Matrix) Flattening() *Matrix {
result := &Matrix{
content: make([][]float64, 1),
}
for i := 0; i < len(matrix.content); i++ {
for j := 0; j < len(matrix.content[i]); j++ {
result.content[0] = append(result.content[0], matrix.content[i][j])
}
}
return result
}
// Transpose the input matrix (A^T)
func (matrix *Matrix) Transpose() *Matrix {
result := &Matrix{
content: make([][]float64, len(matrix.content[0])),
}
for i := 0; i < len(matrix.content); i++ {
for j := 0; j < len(matrix.content[0]); j++ {
result.content[j] = append(result.content[j], matrix.content[i][j])
}
}
return result
}