-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmatrix.go
More file actions
525 lines (450 loc) · 13.7 KB
/
matrix.go
File metadata and controls
525 lines (450 loc) · 13.7 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
package matrix
import (
"fmt"
"math"
"sort"
)
type Col float64
type Row []Col
type Matrix []Row
// Print a matrix
func (matrix Matrix) Print() {
for _, v := range matrix {
fmt.Println(v)
}
}
// Copy creates a copy of a matrix and returns it
func (matrix Matrix) Copy() Matrix {
rows := make([]Row, matrix.Shape()["rows"])
for i := range rows {
rows[i] = make(Row, matrix.Shape()["cols"])
for j := range matrix[i] {
rows[i][j] = matrix[i][j]
}
}
var newMatrix Matrix = rows
return newMatrix
}
// ToArray converts the matrix to an array in the form [][]float64 and returns it
func (matrix Matrix) ToArray() [][]float64 {
arr := make([][]float64, matrix.Shape()["rows"])
for i := range matrix {
arr[i] = make([]float64, matrix.Shape()["cols"])
for j := range matrix[i] {
arr[i][j] = float64(matrix[i][j])
}
}
return arr
}
// Shape gives the shape of a matrix in a map includes 'cols' and 'rows' index
// matrix.Shape()["rows"] -> row count
// matrix.Shape()["cols"] -> column count
func (matrix Matrix) Shape() map[string]int {
shape := make(map[string]int)
shape["rows"] = len(matrix)
if shape["rows"] == 0 {
shape["cols"] = 0
} else {
shape["cols"] = len(matrix[0])
}
return shape
}
// T returns the transpose of a matrix
func (matrix Matrix) T() Matrix {
new_matrix := Zeros(matrix.Shape()["cols"], matrix.Shape()["rows"])
for row_index, _ := range matrix {
for col_index := range matrix[row_index] {
new_matrix[col_index][row_index] = matrix[row_index][col_index]
}
}
return new_matrix
}
// Dot performs the matrix multiplication and returns the result matrix.
// You can multiply the matrix with another matrix.
func (matrix Matrix) Dot(mx Matrix) Matrix {
if matrix.Shape()["cols"] != mx.Shape()["rows"] {
panic("must be n = p for matrix multiplication")
}
new_matrix := Zeros(matrix.Shape()["rows"], mx.Shape()["cols"])
for i := 0; i < matrix.Shape()["rows"]; i++ {
for j := 0; j < mx.Shape()["cols"]; j++ {
for k := 0; k < matrix.Shape()["cols"]; k++ {
new_matrix[i][j] += matrix[i][k] * mx[k][j]
}
}
}
return new_matrix
}
// Add
// Adds two matrices and returns the result matrix.
func (matrix Matrix) Add(mx Matrix) Matrix {
if matrix.Shape()["cols"] != mx.Shape()["cols"] || matrix.Shape()["rows"] != mx.Shape()["rows"] {
panic("the matrices must be in the same size.")
}
for i := 0; i < len(matrix); i++ {
for j := 0; j < len(matrix[0]); j++ {
mx[i][j] = mx[i][j] + matrix[i][j]
}
}
return mx
}
// Subtract
// Subtracts two matrices and returns the result matrix.
func (matrix Matrix) Subtract(mx Matrix) Matrix {
if matrix.Shape()["cols"] != mx.Shape()["cols"] || matrix.Shape()["rows"] != mx.Shape()["rows"] {
panic("the matrices must be in the same size.")
}
newMatrix := matrix.Copy()
for i := range newMatrix {
for j := range newMatrix[i] {
newMatrix[i][j] -= mx[i][j]
}
}
return newMatrix
}
// Plus
// Sums all values in the matrix with the value given as a parameter and returns the result matrix
func (matrix Matrix) Plus(value Col) Matrix {
rows := make([]Row, matrix.Shape()["rows"])
for i := range rows {
rows[i] = make(Row, matrix.Shape()["cols"])
for j := range matrix[i] {
rows[i][j] = matrix[i][j] + value
}
}
var newMatrix Matrix = rows
return newMatrix
}
// Minus subtracts the value given as a parameter from all values in the matrix and returns the result matrix
func (matrix Matrix) Minus(value Col) Matrix {
return matrix.Plus(-value)
}
// Multiply multiplies all values in the matrix with the value given as a parameter and returns the result matrix
func (matrix Matrix) Multiply(value float64) Matrix {
newMatrix := matrix.Copy()
for i := range newMatrix {
for j := range newMatrix[i] {
newMatrix[i][j] = newMatrix[i][j] * Col(value)
}
}
return newMatrix
}
// Divide divides all values in the matrix and the value given as a parameter and returns the result matrix
func (matrix Matrix) Divide(value float64) Matrix {
return matrix.Multiply(1 / value)
}
// Apply applies a function given as a parameter for all values in the matrix and returns the result matrix
// The function takes a value of type 'Col' as a parameter and returns it. Operations are performed within the function.
func (matrix Matrix) Apply(f func(x Col) Col) Matrix {
rows := make([]Row, matrix.Shape()["rows"])
for i := range rows {
rows[i] = make(Row, matrix.Shape()["cols"])
for j := range matrix[i] {
rows[i][j] = f(matrix[i][j])
}
}
var newMatrix Matrix = rows
return newMatrix
}
// Sum returns the sum of the values in the matrix
func (matrix Matrix) Sum() float64 {
var sum Col = 0
for _, r := range matrix {
for _, c := range r {
sum += c
}
}
return float64(sum)
}
// Mean returns the mean of the values in the matrix
func (matrix Matrix) Mean() float64 {
return matrix.Sum() / float64((matrix.Shape()["cols"] * matrix.Shape()["rows"]))
}
// Variance returns the variance of the values in the matrix
func (matrix Matrix) Variance() float64 {
var sum float64 = 0
mean := matrix.Mean()
for row := range matrix {
for col := range matrix[row] {
sum += math.Pow((float64(matrix[row][col]) - mean), 2)
}
}
return sum / float64(matrix.Shape()["cols"]*matrix.Shape()["rows"])
}
// Std returns the standard deviation of the values in the matrix
func (matrix Matrix) Std() float64 {
return math.Sqrt(matrix.Variance())
}
// Max returns the max value of matrix
func (matrix Matrix) Max() float64 {
var values []float64
for r := range matrix {
for c := range matrix[r] {
values = append(values, float64(matrix[r][c]))
}
}
sort.Float64s(values)
return values[len(values)-1]
}
// Min returns the min value of matrix
func (matrix Matrix) Min() float64 {
var values []float64
for r := range matrix {
for c := range matrix[r] {
values = append(values, float64(matrix[r][c]))
}
}
sort.Float64s(values)
return values[0]
}
// JoinRows adds new rows to the matrix and returns the result matrix
// The 'rows' parameter is an array of rows to be added.
// The 'index' parameter specifies from which index new rows will be inserted.
func (matrix Matrix) JoinRows(rows []Row, index int) Matrix {
var mx Matrix = rows
if len(matrix) == 0 {
var newMatrix Matrix = rows
return newMatrix
}
if mx.Shape()["cols"] != matrix.Shape()["cols"] {
panic("the matrices must have same column size.")
}
if index > len(matrix)-1 {
panic("index out of range")
}
if index == -1 {
index = len(matrix)
}
newMatrix := Zeros(matrix.Shape()["rows"]+mx.Shape()["rows"], matrix.Shape()["cols"])
row_index := 0
for i := 0; i < index; i++ {
newMatrix[i] = matrix[i]
row_index++
}
for i := index; i < index+len(mx); i++ {
newMatrix[i] = mx[i-index]
row_index++
}
for i := index; i < len(matrix); i++ {
newMatrix[row_index] = matrix[i]
row_index++
}
return newMatrix
}
// RemoveRow removes the row at given index
func (matrix Matrix) RemoveRow(index int) Matrix {
if index >= matrix.Shape()["rows"] {
panic("index out of range")
}
if index == len(matrix)-1 {
return matrix[:index]
}
return matrix[:index].JoinRows(matrix[index+1:], -1)
}
// MultiplyRow multiplies the row of the matrix at the given index by the value given as a parameter and returns the result matrix
func (matrix Matrix) MultiplyRow(rowIndex int, value Col) Matrix {
if rowIndex >= len(matrix) {
panic("index out of range")
}
newMatrix := matrix.Copy()
for i := range newMatrix[rowIndex] {
newMatrix[rowIndex][i] *= value
}
return newMatrix
}
// SwapRows swaps two lines in given indexes and returns the result matrix
func (matrix Matrix) SwapRows(firstIndex, secondIndex int) Matrix {
if firstIndex >= len(matrix) || secondIndex >= len(matrix) {
panic("index out of range")
}
newMatrix := matrix.Copy()
firstRow := newMatrix[firstIndex]
newMatrix[firstIndex] = newMatrix[secondIndex]
newMatrix[secondIndex] = firstRow
return newMatrix
}
// AddRows sums one row in the matrix with another and returns the result matrix
// The 'destination' parameter refers to the row on which the sum operation will be performed.
// The 'source' parameter indicates which index row will be aggregated with the other.
// At the end of the operation, only the destination row is changed.
func (matrix Matrix) AddRows(destination, source int) Matrix {
if destination >= len(matrix) || source >= len(matrix) {
panic("index out of range")
}
newMatrix := matrix.Copy()
for i := range matrix[destination] {
newMatrix[destination][i] += newMatrix[source][i]
}
return newMatrix
}
// PlusRow sums the row of a matrix at the given index with the row given as a parameter on a column basis and returns the result matrix
func (matrix Matrix) PlusRow(index int, row []Col) Matrix {
if index >= len(matrix) {
panic("index out of range")
}
newMatrix := matrix.Copy()
for i := range newMatrix[index] {
newMatrix[index][i] += row[i]
}
return newMatrix
}
// GetColumn Returns column at given index as 'Col' array ([]Col)
func (matrix Matrix) GetColumn(colIndex int) []Col {
var col []Col
for i := range matrix {
col = append(col, matrix[i][colIndex])
}
return col
}
// JoinColumn adds new rows to the matrix and returns the result matrix
// The index parameter specifies which index the column will be added to.
func (matrix Matrix) JoinColumn(newCol []Col, index int) Matrix {
if matrix.Shape()["rows"] != len(newCol) {
panic("the length of the column to be inserted must be the same as the number of rows of the matrix")
}
if index > matrix.Shape()["cols"] {
panic("index out of range")
}
if index == -1 {
index = matrix.Shape()["cols"]
}
newMatrix := Zeros(matrix.Shape()["rows"], matrix.Shape()["cols"]+1)
for row := range newMatrix {
for i := 0; i < index; i++ {
newMatrix[row][i] = matrix[row][i]
}
newMatrix[row][index] = Col(newCol[row])
for j := index + 1; j < newMatrix.Shape()["cols"]; j++ {
newMatrix[row][j] = matrix[row][j-1]
}
}
return newMatrix
}
// RemoveColumn deletes column at given index and returns the result matrix
func (matrix Matrix) RemoveColumn(index int) Matrix {
if index >= matrix.Shape()["cols"] {
panic("index out of range")
}
if index == -1 {
index = len(matrix) - 1
}
newMatrix := make(Matrix, len(matrix))
for i := 0; i < matrix.Shape()["cols"]; i++ {
if i == index {
continue
}
newMatrix = newMatrix.JoinColumn(matrix.GetColumn(i), -1)
}
return newMatrix
}
// UpperTriangle creates the upper triangle matrix and returns the result matrix
func (matrix Matrix) UpperTriangle() Matrix {
newMatrix := matrix.Copy()
row_index := len(matrix) - 1
for newMatrix[0][0] == 0 {
newMatrix = newMatrix.SwapRows(0, row_index)
row_index--
if row_index < 0 {
panic("all columns is 0 in 0th index")
}
}
for i := range newMatrix {
multiplication_value := newMatrix[i][i]
for j := i + 1; j < len(newMatrix); j++ {
newMatrix = newMatrix.PlusRow(j, newMatrix.MultiplyRow(i, -(newMatrix[j][i] / multiplication_value))[i])
}
}
return newMatrix
}
// LowerTriangle creates the lower triangle matrix and returns the result matrix
func (matrix Matrix) LowerTriangle() Matrix {
newMatrix := matrix.Copy()
row_index := 0
for newMatrix[len(matrix)-1][len(matrix)-1] == 0 {
newMatrix = newMatrix.SwapRows(0, row_index)
row_index++
if row_index > len(matrix) {
panic("all columns is 0 in 0th index")
}
}
for i := len(newMatrix) - 1; i >= 0; i-- {
multiplication_value := newMatrix[i][i]
for j := i - 1; j >= 0; j-- {
newMatrix = newMatrix.PlusRow(j, newMatrix.MultiplyRow(i, -(newMatrix[j][i] / multiplication_value))[i])
}
}
return newMatrix
}
// Inv returns the inverse of a matrix
func (matrix Matrix) Inv() Matrix {
newMatrix := matrix.Copy()
unitMatrix := UnitMatrix(matrix.Shape()["rows"], matrix.Shape()["cols"])
row_index := len(matrix) - 1
for newMatrix[0][0] == 0 {
newMatrix = newMatrix.SwapRows(0, row_index)
row_index--
if row_index < 0 {
panic("all columns is 0 in 0th index")
}
}
for i := range newMatrix {
multiplication_value := newMatrix[i][i]
for j := i + 1; j < len(newMatrix); j++ {
v := -(newMatrix[j][i] / multiplication_value)
newMatrix = newMatrix.PlusRow(j, newMatrix.MultiplyRow(i, v)[i])
unitMatrix = unitMatrix.PlusRow(j, unitMatrix.MultiplyRow(i, v)[i])
}
}
row_index = 0
for newMatrix[len(matrix)-1][len(matrix)-1] == 0 {
newMatrix = newMatrix.SwapRows(0, row_index)
row_index++
if row_index > len(matrix) {
panic("all columns is 0 in 0th index")
}
}
for i := len(newMatrix) - 1; i >= 0; i-- {
multiplication_value := newMatrix[i][i]
for j := i - 1; j >= 0; j-- {
v := -(newMatrix[j][i] / multiplication_value)
newMatrix = newMatrix.PlusRow(j, newMatrix.MultiplyRow(i, v)[i])
unitMatrix = unitMatrix.PlusRow(j, unitMatrix.MultiplyRow(i, v)[i])
}
}
for i := range newMatrix {
multiplication_value := 1 / newMatrix[i][i]
newMatrix = newMatrix.MultiplyRow(i, multiplication_value)
unitMatrix = unitMatrix.MultiplyRow(i, multiplication_value)
}
return unitMatrix
}
// RoundValues rounds the values in the matrix
func (matrix Matrix) RoundValues() Matrix {
newMatrix := matrix.Copy()
for i := range newMatrix {
for j := range newMatrix[i] {
newMatrix[i][j] = Col(math.Round(float64(newMatrix[i][j])*10000) / 10000)
}
}
return newMatrix
}
// Det returns determinant of the matrix
func (matrix Matrix) Det() float64 {
if matrix.Shape()["rows"] != matrix.Shape()["cols"] {
panic("the size of rows and cols must be same")
}
if matrix.Shape()["rows"] <= 0 || matrix.Shape()["cols"] <= 0 {
panic("empty matrix")
}
if matrix.Shape()["rows"] == 1 && matrix.Shape()["cols"] == 1 {
return float64(matrix[0][0])
}
row := matrix[0]
det := 0.0
for i := range row {
a := float64(matrix[0][i])
cofactor := math.Pow(-1, float64(i)) * matrix.RemoveRow(0).RemoveColumn(i).Det()
det += (a * cofactor)
}
return det
}