/
matrix.js
4464 lines (4214 loc) · 108 KB
/
matrix.js
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Complex from './complex.js'
import Tensor from './tensor.js'
const normal_random = (m, s) => {
const std = Math.sqrt(s)
const x = Math.random()
const y = Math.random()
const X = Math.sqrt(-2 * Math.log(x)) * Math.cos(2 * Math.PI * y)
const Y = Math.sqrt(-2 * Math.log(x)) * Math.sin(2 * Math.PI * y)
return [X * std + m, Y * std + m]
}
/**
* Exception for matrix class
*/
export class MatrixException extends Error {
/**
* @param {string} message Error message
* @param {*} value Some value
*/
constructor(message, value) {
super(message)
this.value = value
this.name = 'MatrixException'
}
}
/**
* Matrix class
*/
export default class Matrix {
/**
* @param {number} rows Number of rows
* @param {number} cols Number of columns
* @param {number | Array<number> | Array<Array<number>>} [values] Initial values
*/
constructor(rows, cols, values) {
if (!values) {
this._value = Array(rows * cols).fill(0)
} else if (!Array.isArray(values)) {
this._value = Array(rows * cols).fill(values)
} else if (Array.isArray(values[0])) {
this._value = values.flat()
} else {
this._value = values
}
this._size = [rows, cols]
}
/**
* Returns a matrix filled with 0.
*
* @param {number} rows Number of rows
* @param {number} cols Number of columns
* @returns {Matrix} Matrix filled with 0
*/
static zeros(rows, cols) {
return new Matrix(rows, cols, Array(rows * cols).fill(0))
}
/**
* Returns a matrix filled with 1.
*
* @param {number} rows Number of rows
* @param {number} cols Number of columns
* @returns {Matrix} Matrix filled with 1
*/
static ones(rows, cols) {
return new Matrix(rows, cols, Array(rows * cols).fill(1))
}
/**
* Returns a identity matrix.
*
* @param {number} rows Number of rows
* @param {number} cols Number of columns
* @param {number} [init] Diagonal values
* @returns {Matrix} Identity matrix
*/
static eye(rows, cols, init = 1) {
const mat = new Matrix(rows, cols)
const rank = Math.min(rows, cols)
for (let i = 0; i < rank; i++) {
mat._value[i * cols + i] = init
}
return mat
}
/**
* Returns a matrix initialized uniform random values.
*
* @param {number} rows Number of rows
* @param {number} cols Number of columns
* @param {number} [min] Minimum value of the Matrix (include)
* @param {number} [max] Maximum value of the Matrix (exclude)
* @returns {Matrix} Matrix initialized uniform random values
*/
static random(rows, cols, min = 0, max = 1) {
const mat = new Matrix(rows, cols)
for (let i = 0; i < mat.length; i++) {
mat._value[i] = Math.random() * (max - min) + min
}
return mat
}
/**
* Returns a matrix initialized uniform random integer values.
*
* @param {number} rows Number of rows
* @param {number} cols Number of columns
* @param {number} [min] Minimum value of the Matrix (include)
* @param {number} [max] Maximum value of the Matrix (include)
* @returns {Matrix} Matrix initialized uniform random values
*/
static randint(rows, cols, min = 0, max = 1) {
const mat = new Matrix(rows, cols)
for (let i = 0; i < mat.length; i++) {
mat._value[i] = Math.floor(Math.random() * (max - min + 1) + min)
}
return mat
}
/**
* Returns a matrix initialized normal random values.
*
* @param {number} rows Number of rows
* @param {number} cols Number of columns
* @param {number | number[]} [myu] Mean value(s) of each columns
* @param {number | Array<Array<number>>} [sigma] Variance value or covariance matrix of each columns
* @returns {Matrix} Matrix initialized normal random values
*/
static randn(rows, cols, myu = 0, sigma = 1) {
const mat = new Matrix(rows, cols)
if (Array.isArray(myu)) {
myu = new Matrix(1, myu.length, myu)
}
if (Array.isArray(sigma)) {
sigma = Matrix.fromArray(sigma)
}
if (!(myu instanceof Matrix) && !(sigma instanceof Matrix)) {
for (let i = 0; i < mat.length; i += 2) {
const nr = normal_random(myu, sigma)
mat._value[i] = nr[0]
if (i + 1 < mat.length) {
mat._value[i + 1] = nr[1]
}
}
return mat
}
if (!(myu instanceof Matrix)) {
myu = new Matrix(1, cols, myu)
} else if (myu.rows === cols || myu.cols === 1) {
myu = myu.t
}
if (myu.cols !== cols || myu.rows !== 1) {
throw new MatrixException("'myu' cols must be same as 'cols' and rows must be 1.")
}
if (!(sigma instanceof Matrix)) {
sigma = Matrix.eye(cols, cols, sigma)
} else if (sigma.rows !== cols || sigma.cols !== cols) {
throw new MatrixException("'sigma' cols and rows must be same as 'cols'.")
}
const L = sigma.cholesky()
for (let i = 0; i < mat.length; i += 2) {
const nr = normal_random(0, 1)
mat._value[i] = nr[0]
if (i + 1 < mat.length) {
mat._value[i + 1] = nr[1]
}
}
const smat = mat.dot(L.t)
smat.add(myu)
return smat
}
/**
* Returns a diagonal matrix.
*
* @param {(number | Matrix)[]} d Diagonal values
* @returns {Matrix} Diagonal matrix
*/
static diag(d) {
let n = 0
let m = 0
for (const v of d) {
if (typeof v === 'number') {
n++
m++
} else {
n += v.rows
m += v.cols
}
}
const mat = new Matrix(n, m)
for (let k = 0, i = 0, j = 0; i < n; k++) {
const dk = d[k]
if (typeof dk === 'number') {
mat._value[i * m + j] = dk
i++
j++
} else {
mat.set(i, j, dk)
i += dk.rows
j += dk.cols
}
}
return mat
}
/**
* Returns a matrix from some value.
*
* @param {Matrix | Array<Array<number>> | Array<number> | number} arr Original values
* @returns {Matrix} Matrix from some value
*/
static fromArray(arr) {
if (arr instanceof Matrix) {
return arr
} else if (!Array.isArray(arr)) {
return new Matrix(1, 1, arr)
} else if (arr.length === 0) {
return new Matrix(0, 0)
} else if (!Array.isArray(arr[0])) {
return new Matrix(arr.length, 1, arr)
}
return new Matrix(arr.length, arr[0].length, arr)
}
/**
* Dimension of the matrix.
*
* @type {number}
*/
get dimension() {
return this._size.length
}
/**
* Sizes of the matrix.
*
* @type {number[]}
*/
get sizes() {
return this._size
}
/**
* Number of all elements in the matrix.
*
* @type {number}
*/
get length() {
return this._size[0] * this._size[1]
}
/**
* Number of rows of the matrix.
*
* @type {number}
*/
get rows() {
return this._size[0]
}
/**
* Number of columns of the matrix.
*
* @type {number}
*/
get cols() {
return this._size[1]
}
/**
* Elements in the matrix.
*
* @type {number[]}
*/
get value() {
return this._value
}
/**
* Transpose matrix.
*
* @type {Matrix}
*/
get t() {
return this.transpose()
}
/**
* Iterate over the elements.
*
* @yields {number}
*/
*[Symbol.iterator]() {
yield* this._value
}
/**
* Returns a nested array represented this matrix.
*
* @returns {Array<Array<number>>} Nested array
*/
toArray() {
const arr = []
const n = this.cols
for (let i = 0; i < this.length; i += n) {
arr.push(this._value.slice(i, i + n))
}
return arr
}
/**
* Returns the only element.
*
* @returns {number} The only element
*/
toScaler() {
if (this.rows !== 1 || this.cols !== 1) {
throw new MatrixException('The matrix cannot convert to scaler.')
}
return this._value[0]
}
/**
* Returns a string represented this matrix.
*
* @returns {string} String represented this matrix
*/
toString() {
let s = '['
for (let i = 0; i < this.rows; i++) {
if (i > 0) s += ',\n '
s += '['
for (let j = 0; j < this.cols; j++) {
if (j > 0) s += ', '
s += this._value[i * this.cols + j]
}
s += ']'
}
return s + ']'
}
/**
* Returns a copy of this matrix.
*
* @param {Matrix} [dst] Destination matrix
* @returns {Matrix} Copied matrix
*/
copy(dst) {
if (dst === this) {
return this
} else if (dst) {
dst._size = [].concat(this._size)
this._value.forEach((v, i) => (dst._value[i] = v))
return dst
}
return new Matrix(this.rows, this.cols, [].concat(this._value))
}
/**
* Returns this matrix is equals to the others.
*
* @param {*} other Check tensor
* @param {number} [tol] Tolerance to be recognized as the same
* @returns {boolean} `true` if equal
*/
equals(other, tol = 0) {
if (other instanceof Matrix) {
if (this._size[0] !== other._size[0] || this._size[1] !== other._size[1]) {
return false
}
for (let i = this.length - 1; i >= 0; i--) {
if (Math.abs(this._value[i] - other._value[i]) > tol) {
return false
}
}
return true
}
return false
}
/**
* Returns a value at the position.
*
* @param {number | [number, number]} r Row index or index values
* @param {number} [c] Column index
* @returns {number} Value at the position
*/
at(r, c) {
if (Array.isArray(r)) {
;[r, c] = r
}
if (r < 0 || this.rows <= r || c < 0 || this.cols <= c) throw new MatrixException('Index out of bounds.')
return this._value[r * this.cols + c]
}
/**
* Set a value at the position.
*
* @param {number | [number, number]} r Row index or index values. If this value is an array, the next argument should be the value to be set
* @param {number | Matrix} c Column index or the value to be set
* @param {number | Matrix} [value] The value to be set
* @returns {number=} Old value
*/
set(r, c, value) {
if (Array.isArray(r)) {
value = c
;[r, c] = r
}
if (value instanceof Matrix) {
if (r < 0 || this.rows <= r + value.rows - 1 || c < 0 || this.cols <= c + value.cols - 1) {
throw new MatrixException('Index out of bounds.')
}
for (let i = 0; i < value.rows; i++) {
for (let j = 0; j < value.cols; j++) {
this._value[(i + r) * this.cols + j + c] = value._value[i * value.cols + j]
}
}
return null
} else {
if (r < 0 || this.rows <= r || c < 0 || this.cols <= c) throw new MatrixException('Index out of bounds.')
const old = this._value[r * this.cols + c]
this._value[r * this.cols + c] = value
return old
}
}
/**
* Returns a row matrix at r.
*
* @param {number | number[] | boolean[]} r Indexes of rows, or an array of boolean values where the row to be selected is true.
* @returns {Matrix} Row selected matrix
*/
row(r) {
if (Array.isArray(r)) {
if (typeof r[0] === 'boolean') {
if (r.length !== this.rows) {
throw new MatrixException('Length is invalid.')
}
const rp = []
for (let i = 0; i < r.length; i++) {
if (r[i]) {
rp.push(i)
}
}
r = rp
}
if (r.some(v => v < 0 || this.rows <= v)) {
throw new MatrixException('Index out of bounds.')
}
const mat = new Matrix(r.length, this.cols)
for (let i = 0; i < r.length; i++) {
for (let j = 0; j < this.cols; j++) {
mat._value[i * this.cols + j] = this._value[r[i] * this.cols + j]
}
}
return mat
} else {
if (r < 0 || this.rows <= r) throw new MatrixException('Index out of bounds.')
return new Matrix(1, this.cols, this._value.slice(r * this.cols, (r + 1) * this.cols))
}
}
/**
* Returns a col matrix at c.
*
* @param {number | number[] | boolean[]} c Indexes of columns, or an array of boolean values where the column to be selected is true.
* @returns {Matrix} Column selected matrix
*/
col(c) {
if (Array.isArray(c)) {
if (typeof c[0] === 'boolean') {
if (c.length !== this.cols) {
throw new MatrixException('Length is invalid.')
}
const cp = []
for (let i = 0; i < c.length; i++) {
if (c[i]) {
cp.push(i)
}
}
c = cp
}
if (c.some(v => v < 0 || this.cols <= v)) {
throw new MatrixException('Index out of bounds.')
}
const mat = new Matrix(this.rows, c.length)
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < c.length; j++) {
mat._value[i * c.length + j] = this._value[i * this.cols + c[j]]
}
}
return mat
} else {
if (c < 0 || this.cols <= c) throw new MatrixException('Index out of bounds.')
const mat = new Matrix(this.rows, 1)
for (let i = 0; i < this.rows; i++) {
mat._value[i] = this._value[i * this.cols + c]
}
return mat
}
}
/**
* Returns sliced matrix.
*
* @param {number} from Start index
* @param {number} to End index
* @param {number} [axis] Axis to be sliced
* @returns {Matrix} Sliced matrix
*/
slice(from, to, axis = 0) {
if (typeof from !== 'number') {
from = 0
}
if (typeof to !== 'number') {
to = this._size[axis]
}
if (from < 0 || this._size[axis] < from || to < 0 || this._size[axis] < to) {
throw new MatrixException('Index out of bounds.')
} else if (from > to) {
throw new MatrixException("'to' must be greater than or equals to 'from'.")
}
if (axis === 0) {
const mat = new Matrix(to - from, this.cols)
mat._value = this._value.slice(from * this.cols, to * this.cols)
return mat
} else if (axis === 1) {
const mat = new Matrix(this.rows, to - from)
for (let i = 0; i < mat.rows; i++) {
for (let j = 0; j < mat.cols; j++) {
mat._value[i * mat.cols + j] = this._value[i * this.cols + j + from]
}
}
return mat
} else {
throw new MatrixException('Invalid axis.')
}
}
/**
* Returns the sub-matrix corresponding to position.
*
* @param {number} [rows_from] Start row index
* @param {number} [cols_from] Start column index
* @param {number} [rows_to] End row index(exclusive)
* @param {number} [cols_to] End column index(exclusive)
* @returns {Matrix} Sub matrix
*/
block(rows_from, cols_from, rows_to, cols_to) {
if (typeof rows_from !== 'number') {
rows_from = 0
}
if (typeof cols_from !== 'number') {
cols_from = 0
}
if (typeof rows_to !== 'number') {
rows_to = this.rows
}
if (typeof cols_to !== 'number') {
cols_to = this.cols
}
if (
rows_from < 0 ||
this.rows < rows_from ||
rows_to < 0 ||
this.rows < rows_to ||
cols_from < 0 ||
this.cols < cols_from ||
cols_to < 0 ||
this.cols < cols_to
) {
throw new MatrixException('Index out of bounds.')
} else if (rows_from > rows_to) {
throw new MatrixException("'rows_to' must be greater than or equals to 'rows_from'.")
} else if (cols_from > cols_to) {
throw new MatrixException("'cols_to' must be greater than or equals to 'cols_from'.")
}
const mat = new Matrix(rows_to - rows_from, cols_to - cols_from)
for (let i = 0; i < mat.rows; i++) {
for (let j = 0; j < mat.cols; j++) {
mat._value[i * mat.cols + j] = this._value[(i + rows_from) * this.cols + j + cols_from]
}
}
return mat
}
/**
* Remove specified indexes.
*
* @param {number | number[]} idx Remove index
* @param {number} [axis] Axis to be removed
*/
remove(idx, axis = 0) {
if (axis === 0) {
if (Array.isArray(idx)) {
if (idx.some(v => v < 0 || this.rows <= v)) {
throw new MatrixException('Index out of bounds.')
}
idx = [...new Set(idx)]
idx.sort((a, b) => b - a)
for (let i = 0; i < idx.length; i++) {
this._value.splice(idx[i] * this.cols, this.cols)
}
this._size[0] -= idx.length
} else {
if (idx < 0 || this.rows <= idx) throw new MatrixException('Index out of bounds.')
this._value.splice(idx * this.cols, this.cols)
this._size[0]--
}
} else if (axis === 1) {
if (Array.isArray(idx)) {
if (idx.some(v => v < 0 || this.cols <= v)) {
throw new MatrixException('Index out of bounds.')
}
idx = [...new Set(idx)]
idx.sort((a, b) => a - b)
let si = 0,
di = 0
for (let i = 0; i < this.rows; i++) {
for (let j = 0, p = 0; j < this.cols; j++, si++) {
if (idx[p] === j) {
p++
continue
}
this._value[di++] = this._value[si]
}
}
this._size[1] -= idx.length
this._value.length = this.length
} else {
if (idx < 0 || this.cols <= idx) throw new MatrixException('Index out of bounds.')
let si = 0,
di = 0
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++, si++) {
if (idx === j) {
continue
}
this._value[di++] = this._value[si]
}
}
this._size[1]--
this._value.length = this.length
}
} else {
throw new MatrixException('Invalid axis.')
}
}
/**
* Remove specified indexes.
*
* @param {function (Matrix): boolean} cond Remove condition function. Remove if it returns `true`
* @param {number} [axis] Axis to be removed
*/
removeIf(cond, axis = 0) {
const idx = []
if (axis === 0) {
for (let i = 0; i < this.rows; i++) {
if (cond(this.row(i))) {
idx.push(i)
}
}
} else if (axis === 1) {
for (let i = 0; i < this.cols; i++) {
if (cond(this.col(i))) {
idx.push(i)
}
}
} else {
throw new MatrixException('Invalid axis.')
}
this.remove(idx, axis)
}
/**
* Returns a matrix that sampled along the axis.
*
* @param {number} n Sampled size
* @param {number} [axis] Axis to be sampled
* @returns {[Matrix, number[]]} Sampled matrix and its original indexes
*/
sample(n, axis = 0) {
const k = this.sizes[axis]
const idx = []
for (let i = 0; i < n; i++) {
idx.push(Math.floor(Math.random() * (k - i)))
}
for (let i = n - 1; i >= 0; i--) {
for (let j = n - 1; j > i; j--) {
if (idx[i] <= idx[j]) {
idx[j]++
}
}
}
if (axis === 0) {
return [this.row(idx), idx]
} else if (axis === 1) {
return [this.col(idx), idx]
} else {
throw new MatrixException('Invalid axis.')
}
}
/**
* Fill in all the elements with the value.
*
* @param {number} value Filled value
*/
fill(value) {
this._value.fill(value)
}
/**
* Iterate over all the elements and replace the value.
*
* @param {function (number, number[], Matrix): number} cb Mapping function
*/
map(cb) {
for (let i = 0, p = 0; i < this._size[0]; i++) {
for (let j = 0; j < this._size[1]; j++, p++) {
this._value[p] = cb(this._value[p], [i, j], this)
}
}
}
/**
* Returns a matrix that replace all the elements.
*
* @param {Matrix} mat Original matrix
* @param {function (number, number[], Matrix): number} cb Mapping function
* @returns {Matrix} Mapped matrix
*/
static map(mat, cb) {
const map = new Matrix(mat.rows, mat.cols)
for (let i = 0, p = 0; i < mat._size[0]; i++) {
for (let j = 0; j < mat._size[1]; j++, p++) {
map._value[p] = cb(mat._value[p], [i, j], mat)
}
}
return map
}
/**
* Iterate over all the elements.
*
* @param {function (number, number[], Matrix): number} cb Callback function
*/
forEach(cb) {
for (let i = 0, p = 0; i < this._size[0]; i++) {
for (let j = 0; j < this._size[1]; j++, p++) {
cb(this._value[p], [i, j], this)
}
}
}
/**
* Returns transpose matrix.
*
* @returns {Matrix} Transposed matrix
*/
transpose() {
const mat = new Matrix(this.cols, this.rows)
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
mat._value[j * this.rows + i] = this._value[i * this.cols + j]
}
}
return mat
}
/**
* Returns adjoint matrix.
*
* @returns {Matrix} Adjoint matrix
*/
adjoint() {
return this.transpose()
}
/**
* Flip values along the axis.
*
* @param {number} [axis] Axis to be flipped
*/
flip(axis = 0) {
if (axis === 0) {
for (let i = 0; i < this.rows / 2; i++) {
const t = (this.rows - i - 1) * this.cols
for (let j = 0; j < this.cols; j++) {
const tmp = this._value[i * this.cols + j]
this._value[i * this.cols + j] = this._value[t + j]
this._value[t + j] = tmp
}
}
} else if (axis === 1) {
for (let j = 0; j < this.cols / 2; j++) {
const t = this.cols - j - 1
for (let i = 0; i < this.rows; i++) {
const tmp = this._value[i * this.cols + j]
this._value[i * this.cols + j] = this._value[i * this.cols + t]
this._value[i * this.cols + t] = tmp
}
}
} else {
throw new MatrixException('Invalid axis.')
}
}
/**
* Swap the index a and b along the axis.
*
* @param {number} a First index
* @param {number} b Second index
* @param {number} [axis] Axis to be swapped
*/
swap(a, b, axis = 0) {
if (axis === 0) {
if (a < 0 || b < 0 || this.rows <= a || this.rows <= b) throw new MatrixException('Index out of bounds.')
const diff = (b - a) * this.cols
for (let j = a * this.cols; j < (a + 1) * this.cols; j++) {
;[this._value[j], this._value[j + diff]] = [this._value[j + diff], this._value[j]]
}
} else if (axis === 1) {
if (a < 0 || b < 0 || this.cols <= a || this.cols <= b) throw new MatrixException('Index out of bounds.')
const diff = b - a
for (let j = a; j < this.length; j += this.cols) {
;[this._value[j], this._value[j + diff]] = [this._value[j + diff], this._value[j]]
}
} else {
throw new MatrixException('Invalid axis.')
}
}
/**
* Sort values along the axis.
*
* @param {number} [axis] Axis to be sorted
* @returns {number[]} Original index.
*/
sort(axis = 0) {
if (axis === 0) {
const p = Array.from({ length: this.rows }, (_, i) => i)
p.sort((a, b) => {
const ac = a * this.cols
const bc = b * this.cols
for (let i = 0; i < this.cols; i++) {
const ai = this._value[ac + i]
const bi = this._value[bc + i]
const d = ai - bi
if (d !== 0) return d
}
return 0
})
this._value = this.row(p)._value
return p
} else if (axis === 1) {
const p = Array.from({ length: this.cols }, (_, i) => i)
p.sort((a, b) => {
for (let i = 0; i < this.rows; i++) {
const ai = this._value[a + i * this.cols]
const bi = this._value[b + i * this.cols]
const d = ai - bi
if (d !== 0) return d
}
return 0
})
this._value = this.col(p)._value
return p
}
throw new MatrixException('Invalid axis.')
}
/**
* Shuffle values along the axis.
*
* @param {number} [axis] Axis to be shuffled
* @returns {number[]} Original index.
*/
shuffle(axis = 0) {
const idx = Array.from({ length: this._size[axis] }, (_, i) => i)
for (let i = idx.length - 1; i > 0; i--) {
const r = Math.floor(Math.random() * (i + 1))
;[idx[i], idx[r]] = [idx[r], idx[i]]
}
if (axis === 0) {
this._value = this.row(idx)._value
} else if (axis === 1) {
this._value = this.col(idx)._value
} else {
throw new MatrixException('Invalid axis.')
}
return idx
}
/**
* Make it unique in the specified axis.
*
* @param {number} [axis] Axis to be uniqued
* @param {number} [tol] Tolerance to be recognized as the same
* @returns {number[]} Selected indexes
*/
unique(axis = 0, tol = 0) {
const idx = []
if (axis === 0) {
let r = 0
for (let i = 0; i < this.rows; i++) {
let same_k = -1
for (let k = 0; k < i; k++) {
let issame = true
for (let j = 0; issame && j < this.cols; j++) {
if (Math.abs(this._value[i * this.cols + j] - this._value[k * this.cols + j]) > tol) {
issame = false
}
}
if (issame) {
same_k = k
break
}
}
if (same_k < 0) {
for (let j = 0; j < this.cols; j++) {
this._value[r * this.cols + j] = this._value[i * this.cols + j]
}
idx.push(i)
r++
}
}
this._size[0] = r
this._value.length = this.length
} else if (axis === 1) {
for (let j = 0; j < this.cols; j++) {
let hasSame = false
for (let k = 0; !hasSame && k < idx.length; k++) {
hasSame = true
for (let i = 0; hasSame && i < this.rows; i++) {
if (Math.abs(this._value[i * this.cols + j] - this._value[i * this.cols + idx[k]]) > tol) {
hasSame = false
}
}
}
if (!hasSame) {
idx.push(j)
}
}
for (let i = 0, p = 0; i < this.rows; i++) {
for (let j = 0; j < idx.length; j++, p++) {
this._value[p] = this._value[i * this.cols + idx[j]]
}
}
this._size[1] = idx.length
this._value.length = this.length
} else {
throw new MatrixException('Invalid axis.')
}
return idx
}
/**
* Resize this matrix.
*
* @param {number} rows New row size
* @param {number} cols New column size
* @param {number} [init] Value of the extended region
*/
resize(rows, cols, init = 0) {
const newValue = Array(rows * cols).fill(init)
const mr = Math.min(this.rows, rows)
const mc = Math.min(this.cols, cols)
for (let i = 0; i < mr; i++) {
for (let j = 0; j < mc; j++) {
newValue[i * cols + j] = this._value[i * this.cols + j]
}
}
this._value = newValue
this._size = [rows, cols]
}
/**
* Return resized matrix.
*
* @param {Matrix} mat Original matrix
* @param {number} rows New row size
* @param {number} cols New column size
* @param {number} [init] Value of the extended region
* @returns {Matrix} Resized matrix
*/
static resize(mat, rows, cols, init = 0) {
const r = new Matrix(rows, cols)
r.fill(init)
const mr = Math.min(mat.rows, rows)
const mc = Math.min(mat.cols, cols)
for (let i = 0; i < mr; i++) {
for (let j = 0; j < mc; j++) {
r._value[i * cols + j] = mat._value[i * mat.cols + j]