forked from DzananGanic/numericalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix.go
More file actions
370 lines (300 loc) · 8.22 KB
/
matrix.go
File metadata and controls
370 lines (300 loc) · 8.22 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package numericalgo
import "fmt"
import "math"
// Matrix type is the slice of Vectors, with custom methods needed for matrix operations.
type Matrix []Vector
// Dim returns the dimensions of the matrix in the form (rows, columns).
func (m Matrix) Dim() (int, int) {
if m.isNil() {
return 0, 0
}
return len(m), len(m[0])
}
// Invert returns the inverted matrix by using Gauss-Jordan elimination
func (m Matrix) Invert() (Matrix, error) {
if !m.isSquare() {
return nil, fmt.Errorf("Cannot invert non-square Matrix")
}
var rows, _ = m.Dim()
vec := make(Vector, rows)
// 1. Reduction to identity form
for currentRow := 1; currentRow <= rows; currentRow++ {
// Pivoting
p := currentRow
for i := currentRow + 1; i <= rows; i++ {
if math.Abs(m[i-1][currentRow-1]) > math.Abs(m[p-1][currentRow-1]) {
p = i
}
}
// If there exists no element a(k,i) different from zero, matrix is singular and has none or more than one solution
if math.Abs(m[p-1][currentRow-1]) < 1e-10 {
return nil, fmt.Errorf("Matrix is singular")
}
// If we find pivot which is the largest a(i, currentRow), we swap the rows
if p != currentRow {
tmp := m[currentRow-1]
m[currentRow-1] = m[p-1]
m[p-1] = tmp
}
vec[currentRow-1] = float64(p)
mi := m[currentRow-1][currentRow-1]
m[currentRow-1][currentRow-1] = 1.0
// Dividing by mi
div, err := m[currentRow-1].DivideByScalar(mi)
if err != nil {
return nil, err
}
m[currentRow-1] = div
for i := 1; i <= rows; i++ {
if i != currentRow {
mi = m[i-1][currentRow-1]
m[i-1][currentRow-1] = 0.0
for j := 1; j <= rows; j++ {
m[i-1][j-1] -= mi * m[currentRow-1][j-1]
}
}
}
}
// Reverse swapping
for j := rows; j >= 1; j-- {
p := vec[j-1]
if p != float64(j) {
for i := 1; i <= rows; i++ {
tmp := m[i-1][int64(p)-1]
m[i-1][int64(p)-1] = m[i-1][j-1]
m[i-1][j-1] = tmp
}
}
}
return m, nil
}
// Log applies natural logarithm to all the elements of the matrix, and returns the resulting matrix.
func (m Matrix) Log() Matrix {
row, col := m.Dim()
result := make(Matrix, row)
for i := range m {
result[i] = make(Vector, col)
for j := range m[i] {
result[i][j] = math.Log(m[i][j])
}
}
return result
}
// Exp applies e^x to all the elements of the matrix, and returns the resulting matrix.
func (m Matrix) Exp() Matrix {
row, col := m.Dim()
result := make(Matrix, row)
for i := range m {
result[i] = make(Vector, col)
for j := range m[i] {
result[i][j] = math.Exp(m[i][j])
}
}
return result
}
// LeftDivide receives another matrix as a parameter. The method solves the symbolic system of linear equations in matrix form, A*X = B for X. It returns the results in matrix form and error (if there is any).
func (m Matrix) LeftDivide(m2 Matrix) (Matrix, error) {
var r Matrix
mT, err := m.Transpose()
if err != nil {
return r, err
}
mtm, err := mT.MultiplyBy(m)
if err != nil {
return r, err
}
pInv, err := mtm.Invert()
if err != nil {
return r, err
}
pmt, err := pInv.MultiplyBy(mT)
if err != nil {
return r, err
}
r, err = pmt.MultiplyBy(m2)
if err != nil {
return r, err
}
return r, nil
}
func (m Matrix) sumAbs() float64 {
var sum float64
rows, cols := m.Dim()
for i := 0; i < rows; i++ {
for j := 0; j < cols; j++ {
sum += math.Abs(m[i][j])
}
}
return sum
}
func (m Matrix) isSquare() bool {
rows, cols := m.Dim()
return rows == cols
}
// MultiplyBy receives another matrix as a parameter. It multiplies the matrices and returns the resulting matrix and error.
func (m Matrix) MultiplyBy(m2 Matrix) (Matrix, error) {
var r Matrix
_, cols1 := m.Dim()
rows2, _ := m2.Dim()
if cols1 != rows2 {
return r, fmt.Errorf("The number of columns of the 1st matrix must equal the number of rows of the 2nd matrix")
}
for currentRowIndex := range m {
r = append(r, Vector{})
for currentColumnIndex := range m2[0] {
m2Col, err := m2.Col(currentColumnIndex)
if err != nil {
return r, err
}
dot, err := m[currentRowIndex].Dot(m2Col)
if err != nil {
return r, err
}
r[currentRowIndex] = append(r[currentRowIndex], dot)
}
}
return r, nil
}
// InsertCol receives the index and the vector. It adds the provided vector as a column at index k, and returns the resulting matrix and the error (if there is any).
func (m Matrix) InsertCol(k int, c Vector) (Matrix, error) {
var r Matrix
if k < 0 {
return r, fmt.Errorf("Index cannot be less than 0")
} else if _, width := m.Dim(); k > width {
return r, fmt.Errorf("Index cannot be greater than number of columns + 1")
} else if len(c) != len(m) {
return r, fmt.Errorf("Column dimensions must match")
}
for i := 0; i < len(m); i++ {
row := m[i]
expRow := append(row[:k], append(Vector{c[i]}, row[k:]...)...)
r = append(r, expRow)
}
return r, nil
}
// Row receives the index as a parameter. It returns the vector row at provided index and the error (if there is any).
func (m Matrix) Row(i int) (Vector, error) {
if i < 0 {
return nil, fmt.Errorf("Index cannot be negative")
} else if i > len(m) {
return nil, fmt.Errorf("Index cannot be greater than the length")
}
return m[i], nil
}
// Col receives the index as a parameter. It returns the vector column at provided index and the error (if there is any).
func (m Matrix) Col(i int) (Vector, error) {
var r Vector
if i < 0 {
return nil, fmt.Errorf("Index cannot be negative")
} else if i > len(m[0]) {
return nil, fmt.Errorf("Index cannot be greater than the length")
}
for row := range m {
r = append(r, m[row][i])
}
return r, nil
}
// Transpose returns the transposed matrix and the error.
func (m Matrix) Transpose() (Matrix, error) {
var t Matrix
for columnIndex := range m[0] {
column, err := m.Col(columnIndex)
if err != nil {
return t, err
}
t = append(t, column)
}
return t, nil
}
// IsSimilar receives another matrix and tolerance as the parameters. It checks whether the two matrices are similar within the provided tolerance.
func (m Matrix) IsSimilar(m2 Matrix, tol float64) bool {
if m.IsEqual(m2) {
return true
}
if !m.areDimsEqual(m2) {
return false
}
for col := range m {
for row := range m[col] {
if math.Abs(m[col][row]-m2[col][row]) > tol {
return false
}
}
}
return true
}
// IsEqual receives another matrix as a parameter. It returns true if the values of the two matrices are equal, and false otherwise.
func (m Matrix) IsEqual(m2 Matrix) bool {
if m == nil && m2 == nil {
return true
} else if m == nil || m2 == nil {
return false
} else if !m.areDimsEqual(m2) {
return false
}
for row := range m {
for col := range m[row] {
if m[row][col] != m2[row][col] {
return false
}
}
}
return true
}
// Add receives another matrix as a parameter. It adds the two matrices and returns the result matrix and the error (if there is any).
func (m Matrix) Add(m2 Matrix) (Matrix, error) {
rows, cols := m.Dim()
var r = make(Matrix, rows, cols)
if ok, err := m.canPerformOperationsWith(m2); !ok {
return nil, err
}
for row := range m {
for col := range m[row] {
r[row] = append(r[row], m[row][col]+m2[row][col])
}
}
return r, nil
}
// Subtract receives another matrix as a parameter. It subtracts the two matrices and returns the result matrix and the error (if there is any).
func (m Matrix) Subtract(m2 Matrix) (Matrix, error) {
rows, cols := m.Dim()
var r = make(Matrix, rows, cols)
if ok, err := m.canPerformOperationsWith(m2); !ok {
return nil, err
}
for row := range m {
for col := range m[row] {
r[row] = append(r[row], m[row][col]-m2[row][col])
}
}
return r, nil
}
func (m Matrix) areDimsEqual(m2 Matrix) bool {
mRows, mCols := m.Dim()
m2Rows, m2Cols := m2.Dim()
if mRows != m2Rows || mCols != m2Cols {
return false
}
return true
}
func (m Matrix) isNil() bool {
if m == nil {
return true
}
return false
}
func (m Matrix) canPerformOperationsWith(m2 Matrix) (bool, error) {
if m == nil || m2 == nil {
return false, fmt.Errorf("Matrices cannot be nil")
} else if !m.areDimsEqual(m2) {
return false, fmt.Errorf("Matrix dimensions must match")
}
return true, nil
}
// OTHER CONVENIENT METHODS THAT CAN BE IMPLEMENTED:
// TODO: AddRowAt
// TODO: RemoveRowAt
// TODO: RemoveColumnAt
// TODO: Determinant
// TODO: Check for consistent dimensions
// TODO: IsSingular