This repository has been archived by the owner on Jan 2, 2019. It is now read-only.
/
matrix.js
2370 lines (1982 loc) · 74.7 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
/**
* matrix.js
* (C) 2013 Ingo Bürk, admin (at) airblader (dot) de
* This library is protected with the MIT License.
*
* matrix.js is a Javascript library that offers a matrix structure and calculations on matrices,
* such as adding, multiplying, inverting, ...
*
* @author Ingo Bürk
*/
(function (window) {
function isNumber (k) {
return typeof k === 'number';
}
function isInteger (k) {
return isNumber( k ) && (k | 0) === k;
}
function isArray (obj) {
return obj instanceof Array;
}
function isNumberArray (obj) {
for( var i = 0; i < obj.length; i++ ) {
if( !isNumber( obj[i] ) ) {
return false;
}
}
return true;
}
function getNumberWithDefault (obj, defaultValue) {
return (isNumber( obj )) ? obj : defaultValue;
}
function getStringWithDefault (obj, defaultValue) {
return (typeof obj === 'string') ? obj : defaultValue;
}
function getBooleanWithDefault (obj, defaultValue) {
return (typeof obj === 'boolean') ? obj : defaultValue;
}
function isVectorSized (M) {
return M.dim( 'min' ) === 1;
};
function toArray (obj) {
if( isArray( obj ) ) {
return obj;
}
if( !isVectorSized( obj ) ) {
throw new MatrixError( MatrixError.ErrorCodes.DIMENSION_MISMATCH, 'Argument has to be vector' );
}
var elements = (obj.dim( 'max' ) === obj.rows()) ? obj.__getColumn( 1 ) : obj.__getRow( 1 ),
result = [];
for( var i = 1; i <= elements.length; i++ ) {
result.push( elements[i - 1] );
}
return result;
}
function copyArray (arr) {
return [].slice.call( arr );
}
/**
* Static class for utility functions.
* @static
* @constructor
*/
function MatrixUtils () {
throw new Error( 'This cannot be instantiated' );
}
/**
* Error thrown by matrixjs.
* @param {string} code Error code, one of {@link MatrixError.ErrorCodes}
* @param {string} [msg] Additional message string
* @constructor
*/
function MatrixError (code, msg) {
this.name = 'MatrixError';
this.code = code;
this.message = msg;
/** @override */
this.toString = function () {
return this.name + ' [' + this.code + ']: ' + (this.message || 'No message');
}
}
/**
* Error codes for MatrixError.
*/
MatrixError.ErrorCodes = {
/** @expose */ INVALID_PARAMETERS: 'Invalid parameters',
/** @expose */ OUT_OF_BOUNDS: 'Out of bounds',
/** @expose */ DIMENSION_MISMATCH: 'Dimension mismatch',
/** @expose */ MATRIX_IS_SINGULAR: 'Matrix is singular',
/** @expose */ UNKNOWN_TYPE: 'Unknown type',
/** @expose */ SIZE_NOT_GIVEN: 'Size not given'
};
/**
* Creates a new Matrix.
* There is a number of different signatures for the parameter(s) to define the matrix.
* - Use one number n to create a n-by-n matrix filled with zeros.
* - Use two numbers m, n to create a m-by-n matrix filled with zeros.
* - Use an array of arrays, wherein the inner arrays represent entire rows.
* - Use an array of numbers defining the elements from left to right, top to bottom. If no other argument
* is given, the matrix will be assumed to be square. Alternatively, pass two arguments to specify the row and
* column dimension of the matrix. If either one is null/undefined, it will be computed from the other one.
* @example
* new Matrix( 3 );
*
* new Matrix( 2, 3 );
*
* new Matrix( [
* [1,2,3],
* [4,5,6]
* ] );
*
* new Matrix( [1, 2, 3, 4, 5, 6, 7, 8, 9] );
* new Matrix( [1, 2, 3, 4, 5, 6], 2, 3 );
* new Matrix( [1, 2, 3, 4, 5, 6], 2 );
* new Matrix( [1, 2, 3, 4, 5, 6], null, 3 );
* @constructor
* @param {...*} var_args
*/
function Matrix (var_args) {
var args = copyArray( arguments ),
__rows, __columns,
__elements = [];
/**
* @override
* @private
*/
this.___get = function (row, column) {
return __elements[__columns * (row - 1) + column - 1];
};
/**
* @override
* @private
*/
this.___set = function (row, column, value) {
__elements[__columns * (row - 1) + column - 1] = value;
return this;
};
/**
* Get the number of rows.
* @returns {number}
* @override
*/
this.rows = function () {
return __rows;
};
/**
* Get the number of columns.
* @returns {number}
* @override
*/
this.columns = function () {
return __columns;
};
/**
* @override
* @private
*/
this.___getElements = function () {
return __elements;
};
// Constructor
(function () {
if( args.length === 1 && isArray( args[0] ) && args[0].length !== 0 && isArray( args[0][0] ) ) {
__rows = args[0].length;
__columns = -1;
for( var i = 0; i < args[0].length; i++ ) {
if( (args[0][i].length !== __columns && __columns !== -1) ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS,
'Number of columns must be the same for all rows' );
}
if( !isNumberArray( args[0][i] ) ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS, 'Elements must be numbers' );
}
__columns = Math.max( __columns, args[0][i].length );
__elements = __elements.concat( args[0][i] );
}
} else if( args.length >= 1 && args.length <= 3 && isArray( args[0] )
&& ( args[0].length === 0 || isNumber( args[0][0] ) ) ) {
if( !isNumberArray( args[0] ) ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS, 'Elements must be numbers' );
}
__elements = args[0];
var rows = args[1],
columns = args[2];
if( !isNumber( rows ) && !isNumber( columns ) ) {
var dim = Math.sqrt( __elements.length );
rows = dim;
columns = dim;
} else if( !isNumber( rows ) && isInteger( columns ) ) {
rows = __elements.length / columns;
} else if( isInteger( rows ) && !isNumber( columns ) ) {
columns = __elements.length / rows;
}
if( !isInteger( rows ) || !isInteger( columns ) ) {
throw new MatrixError( MatrixError.ErrorCodes.OUT_OF_BOUNDS,
'Array must represent square matrix if no size is given' );
}
__rows = rows;
__columns = columns;
} else if( args.length === 1 && isInteger( args[0] ) ) {
__rows = args[0];
__columns = args[0];
__elements = MatrixUtils.repeat( __rows * __columns, 0 );
} else if( args.length === 2 && isInteger( args[0] ) && isInteger( args[1] ) ) {
__rows = args[0];
__columns = args[1];
__elements = MatrixUtils.repeat( __rows * __columns, 0 );
} else {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS,
'Parameters must match a supported signature' );
}
})();
return this;
}
/**
* TODO documentation
* @constructor
* @param {...*} var_args
*/
function SparseMatrix (var_args) {
var args = copyArray( arguments ),
__rows,
__columns,
__elements = [],
__columnIndicator = [],
__rowPointer = [];
/**
* @override
* @private
*/
this.___get = function (row, column) {
for( var k = __rowPointer[row - 1]; k < __rowPointer[row]; k++ ) {
if( __columnIndicator[k] === column ) {
return __elements[k];
}
}
return 0;
};
/**
* @override
* @private
*/
this.___set = function (row, column, value) {
var index,
hasBeenAssignedBefore = false;
for( var k = __rowPointer[row - 1]; k <= __rowPointer[row]; k++ ) {
index = k;
if( __columnIndicator[k] === column && k !== __rowPointer[row] ) {
hasBeenAssignedBefore = true;
break;
}
}
if( !hasBeenAssignedBefore && value !== 0 ) {
for( var i = row; i < __rowPointer.length; i++ ) {
__rowPointer[i] += 1;
}
__elements.splice( index, 0, value );
__columnIndicator.splice( index, 0, column );
} else if( hasBeenAssignedBefore && value !== 0 ) {
__elements.splice( index, 1, value );
__columnIndicator.splice( index, 1, column );
} else if( hasBeenAssignedBefore ) {
for( var i = row; i < __rowPointer.length; i++ ) {
__rowPointer[i] -= 1;
}
__elements.splice( index, 1 );
__columnIndicator.splice( index, 1 );
}
return this;
};
/** @private */
this.___getElements = function () {
return __elements;
};
/** @private */
this.___getColumnIndicator = function () {
return __columnIndicator;
};
/** @private */
this.___getRowPointer = function () {
return __rowPointer;
};
/**
* Get the number of rows.
* @returns {number}
* @override
*/
this.rows = function () {
return __rows;
};
/**
* Get the number of columns.
* @returns {number}
* @override
*/
this.columns = function () {
return __columns;
};
(function () {
if( args.length >= 1 && args.length <= 2 && isInteger( args[0] )
&& ( args.length === 1 || isInteger( args[1] ) ) ) {
__rows = args[0];
__columns = args[1] || __rows;
__elements = [];
__columnIndicator = [];
__rowPointer = MatrixUtils.repeat( __rows + 1, 0 );
} else if( args.length === 5 && isInteger( args[0] ) && isInteger( args[1] ) && isArray( args[2] )
&& isArray( args[3] ) && isArray( args[4] ) ) {
__rows = args[0];
__columns = args[1];
__elements = args[2];
__columnIndicator = args[3];
__rowPointer = args[4];
if( __elements.indexOf( 0 ) !== -1 ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS,
'Values must not be 0' );
}
if( __rows != __rowPointer.length - 1 ) {
throw new MatrixError( MatrixError.ErrorCodes.OUT_OF_BOUNDS,
'Number of rows is too small' );
}
if( __elements.length !== __columnIndicator.length ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS,
'Arrays for values and column indicators have to be the same size' );
}
if( Math.max.apply( this, __columnIndicator ) > __columns ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS,
'Number of columns has to be bigger than the biggest column index' );
}
} else if( args.length === 1 && args[0] instanceof SparseBuilder ) {
return args[0].build();
} else {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS,
'Parameters must match a supported signature' );
}
})();
return this;
}
/**
* TODO documentation
* @constructor
* @param {...*} var_args
*/
function Vector (var_args) {
var args = copyArray( arguments ),
isRowVector,
__elements = [];
/**
* @override
* @private
*/
this.___get = function (row, column) {
return __elements[(isRowVector) ? (row - 1) : (column - 1)];
};
/**
* @override
* @private
*/
this.___set = function (row, column, value) {
__elements[(isRowVector) ? (row - 1) : (column - 1)] = value;
return this;
};
/**
* Get the number of rows.
* @returns {number}
* @override
*/
this.rows = function () {
return (isRowVector) ? __elements.length : 1;
};
/**
* Get the number of columns.
* @returns {number}
* @override
*/
this.columns = function () {
return (isRowVector) ? 1 : __elements.length;
};
(function () {
// TODO constructor
})();
return this;
}
/**
* TODO documentation
* @constructor
*/
function SparseBuilder () {
var __rows, __columns,
__values = [];
function add (i, j, value) {
__values.push( {
row: i,
column: j,
value: value
} );
}
/**
* @param {number} rows
* @param {number} [columns=rows]
*/
this.size = function (rows, columns) {
__rows = rows;
__columns = getNumberWithDefault( columns, rows );
return this;
};
this.set = function (row, column, value) {
if( !isInteger( __rows ) || !isInteger( __columns ) ) {
throw new MatrixError( MatrixError.ErrorCodes.SIZE_NOT_GIVEN,
'Size has to be specified first' );
}
if( !isNumber( value ) ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS,
'Value is not numeric' );
}
// prevent setting the same entry multiple times
var assignedBefore = __values.filter(function (current) {
return current.row === row && current.column === column;
} ).length;
if( assignedBefore !== 0 ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS,
'Cannot set same entry multiple times' );
}
if( row > __rows || column > __columns ) {
throw new MatrixError( MatrixError.ErrorCodes.OUT_OF_BOUNDS );
}
if( value !== 0 ) {
add( row, column, value );
}
return this;
};
this.build = function () {
__values.sort( function (a, b) {
if( a.row != b.row ) {
return (a.row < b.row) ? -1 : 1;
}
if( a.column != b.column ) {
return (a.column < b.column) ? -1 : 1;
}
return 0;
} );
var elements = [],
rowPointer = MatrixUtils.repeat( __rows + 1, 0 ),
columnIndicator = [],
lastRow = 1;
for( var i = 0; i < __values.length; i++ ) {
var current = __values[i];
elements[i] = current.value;
columnIndicator[i] = current.column;
if( rowPointer[current.row] === 0 ) {
for( var k = lastRow + 1; k <= current.row; k++ ) {
rowPointer[k] = rowPointer[k - 1];
}
}
rowPointer[current.row]++;
lastRow = current.row;
}
rowPointer[__rows] = columnIndicator.length;
return new SparseMatrix( __rows, __columns, elements, columnIndicator, rowPointer );
};
}
/* Matrix */
/**
* Get an entry from the matrix.
* @param {number} row
* @param {number} column
* @returns {number}
*/
Matrix.prototype.get = function (row, column) {
if( !this.isInRange( row, column ) ) {
throw new MatrixError( MatrixError.ErrorCodes.OUT_OF_BOUNDS );
}
return this.___get( row, column );
};
/**
* Set an entry in the matrix.
* Note: This function modifies the instance it is called on.
* @param {number} row
* @param {number} column
* @param {number} value
* @returns {Matrix}
*/
Matrix.prototype.set = function (row, column, value) {
if( !this.isInRange( row, column ) ) {
throw new MatrixError( MatrixError.ErrorCodes.OUT_OF_BOUNDS );
}
if( !isNumber( value ) ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS, 'Value has to be a number' );
}
return this.___set( row, column, value );
};
/**
* Get a row.
* @param {number} row The row index of the row that shall be returned
* @returns {Array.<number>|Matrix}
*/
Matrix.prototype.getRow = function (row) {
if( !this.isInRange( row, null ) ) {
throw new MatrixError( MatrixError.ErrorCodes.OUT_OF_BOUNDS );
}
return this.__getRow( row );
};
/**
* @private
* @ignore
*/
Matrix.prototype.__getRow = function (row) {
var result = [],
columns = this.columns();
for( var i = 1; i <= columns; i++ ) {
result.push( this.___get( row, i ) );
}
return result;
};
/**
* Replace a row.
* Note: This function modifies the instance it is called on.
* @param {number} row The row index of the row to replace
* @param {(Array.<number>|Matrix)} entries An array or Matrix containing the new entries for the row
* @returns {Matrix}
*/
Matrix.prototype.setRow = function (row, entries) {
entries = toArray( entries );
if( !this.isInRange( row, null ) ) {
throw new MatrixError( MatrixError.ErrorCodes.OUT_OF_BOUNDS );
}
if( entries.length !== this.columns() ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS, 'Wrong number of columns in row.' );
}
return this.__setRow( row, entries );
};
/**
* @private
* @ignore
*/
Matrix.prototype.__setRow = function (row, entries) {
var columns = this.columns();
for( var i = 1; i <= columns; i++ ) {
this.___set( row, i, entries[i - 1] );
}
return this;
};
/**
* Get a column.
* @param {number} column The column index of the column that shall be returned
* @returns {Array.<number>}
*/
Matrix.prototype.getColumn = function (column) {
if( !this.isInRange( null, column ) ) {
throw new MatrixError( MatrixError.ErrorCodes.OUT_OF_BOUNDS );
}
return this.__getColumn( column );
};
/**
* @private
* @ignore
*/
Matrix.prototype.__getColumn = function (column) {
var result = [],
rows = this.rows();
for( var i = 1; i <= rows; i++ ) {
result.push( this.___get( i, column ) );
}
return result;
};
/**
* Replace a column.
* Note: This function modifies the instance it is called on.
* @param {number} column The column index of the column to replace
* @param {(Array.<number>|Matrix)} entries An array or matrix containing the new entries for the column
* @returns {Matrix}
*/
Matrix.prototype.setColumn = function (column, entries) {
entries = toArray( entries );
if( !this.isInRange( null, column ) ) {
throw new MatrixError( MatrixError.ErrorCodes.OUT_OF_BOUNDS );
}
if( entries.length !== this.rows() ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS, 'Wrong number of rows in column' );
}
return this.__setColumn( column, entries );
};
/**
* @private
* @ignore
*/
Matrix.prototype.__setColumn = function (column, entries) {
var rows = this.rows();
for( var i = 1; i <= rows; i++ ) {
this.___set( i, column, entries[i - 1] );
}
return this;
};
/**
* Check if matrix has the same dimensions as another matrix.
* @param {Matrix} M
* @returns {boolean}
*/
Matrix.prototype.isSameSizeAs = function (M) {
return ( this.rows() === M.rows() && this.columns() === M.columns() );
};
/**
* Check if the matrix is a square matrix.
* @returns {boolean} True if the number of rows and columns equal, false otherwise.
*/
Matrix.prototype.isSquare = function () {
return this.rows() === this.columns();
};
/**
* Check if the matrix is symmetric.
* @returns {boolean}
*/
Matrix.prototype.isSymmetric = function () {
if( !this.isSquare() ) {
throw new MatrixError( MatrixError.ErrorCodes.DIMENSION_MISMATCH, 'Matrix must be square' );
}
var rows = this.rows();
// shifted loop start because the diagonal doesn't need to be checked
for( var i = 2; i <= rows; i++ ) {
for( var j = 1; j < i; j++ ) {
if( this.___get( i, j ) !== this.___get( j, i ) ) {
return false;
}
}
}
return true;
};
/**
* Check if matrix is triangular.
* @param {string} [mode='both'] What kind of triangular matrix to check for. Possible values are:
* - 'lower': True if lower triangular matrix, false otherwise
* - 'upper': True if upper triangular matrix, false otherwise
* - 'both': True if either lower or upper triangular, false otherwise
* @returns {boolean}
*/
Matrix.prototype.isTriangular = function (mode) {
mode = getStringWithDefault( mode, MatrixUtils.options.isTriangular.mode );
if( !this.isSquare() ) {
throw new MatrixError( MatrixError.ErrorCodes.DIMENSION_MISMATCH, 'Matrix must be square' );
}
switch( mode.toLowerCase() ) {
case 'lower':
return this.__isTriangular( false );
case 'upper':
return this.__isTriangular( true );
case 'both':
return ( this.__isTriangular( true ) || this.__isTriangular( false ) );
default:
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS, 'Mode not supported' );
}
};
/**
* @private
* @ignore
*/
Matrix.prototype.__isTriangular = function (upper) {
var sign = (upper) ? 1 : -1,
diag, num_diag,
rows = this.rows();
for( var i = 1; i < rows; i++ ) {
diag = this.diag( sign * i );
num_diag = diag.length;
for( var j = 0; j < num_diag; j++ ) {
if( diag[j] !== 0 ) {
return false;
}
}
}
return true;
};
/**
* Return a copy of the matrix. This prevents accidental usage of references.
* @returns {Matrix}
*/
Matrix.prototype.copy = function () {
return new Matrix( this.toArray(), this.rows(), this.columns() );
};
/**
* Returns the number of elements in the matrix.
* @returns {number}
*/
Matrix.prototype.size = function () {
return this.rows() * this.columns();
};
/**
* Get the dimensions of the matrix.
* @param {(number|string)} which Define which dimension should be returned. Possible values are:
* - 1 or 'rows' : Number of rows
* - 2 or 'columns' : Number of columns
* - 'max' : Dominant dimension
* - 'min' : Smaller dimension
* @returns {number} Object with the dimensions of requested dimension or just
* the requested dimension.
*/
Matrix.prototype.dim = function (which) {
switch( which ) {
case 1:
case 'rows':
return this.rows();
case 2:
case 'columns':
return this.columns();
case 'max':
return Math.max( this.rows(), this.columns() );
case 'min':
return Math.min( this.rows(), this.columns() );
default:
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS, 'Parameter must match a known value' );
}
};
/**
* Add a matrix.
* If more than one matrix is passed, they will be added in order, i.e. this + M + N + ...
* @param {Matrix} M Matrix
* @returns {Matrix} Component-wise sum of this and M.
*/
Matrix.prototype.add = function (M) {
var rows = this.rows(),
columns = this.columns();
if( arguments.length > 1 ) {
var args = copyArray( arguments );
return this.add.apply( this.add( args.shift() ), args );
}
if( !this.isSameSizeAs( M ) ) {
throw new MatrixError( MatrixError.ErrorCodes.DIMENSION_MISMATCH, 'Matrices must be of the same size' );
}
var Result = new Matrix( rows, columns ),
rowA, rowB;
for( var i = 1; i <= rows; i++ ) {
rowA = this.__getRow( i );
rowB = M.__getRow( i );
for( var j = 0; j < columns; j++ ) {
rowA[j] += rowB[j];
}
Result.__setRow( i, rowA );
}
return Result;
};
/**
* Subtract a matrix.
* If more than one matrix is passed, they wll be subtracted in order, i.e. this - M - N - ...
* @param {Matrix} M Matrix
* @returns {Matrix} Component-wise difference of this and M.
*/
Matrix.prototype.subtract = function (M) {
var rows = this.rows(),
columns = this.columns();
if( arguments.length > 1 ) {
var args = copyArray( arguments );
return this.subtract.apply( this.subtract( args.shift() ), args );
}
if( !this.isSameSizeAs( M ) ) {
throw new MatrixError( MatrixError.ErrorCodes.DIMENSION_MISMATCH, 'Matrices must be of the same size' );
}
var Result = new Matrix( rows, columns ),
rowA, rowB;
for( var i = 1; i <= rows; i++ ) {
rowA = this.__getRow( i );
rowB = M.__getRow( i );
for( var j = 0; j < columns; j++ ) {
rowA[j] -= rowB[j];
}
Result.__setRow( i, rowA );
}
return Result;
};
/**
* Scale with a constant factor (i.e. calculate k * this)
* @param {number} k Factor
* @returns {Matrix} Matrix with all entries multiplied by k.
*/
Matrix.prototype.scale = function (k) {
if( !isNumber( k ) ) {
throw new MatrixError( MatrixError.ErrorCodes.INVALID_PARAMETERS, 'Parameter must be a number' );
}
var rows = this.rows(),
columns = this.columns();
// Trivial cases in which we can spare the multiplications
if( k === 0 ) {
return new Matrix( rows, columns );
}
if( k === 1 ) {
return this;
}
return this.fun( function (value) {
return k * value;
} );
};
/**
* Multiply with another matrix.
* @param {Matrix} M
* @returns {Matrix}
*/
Matrix.prototype.multiply = function (M) {
var dimOuterLeft = this.rows(),
dimInner = this.columns(),
dimOuterRight = M.columns();
if( dimInner !== M.rows() ) {
throw new MatrixError( MatrixError.ErrorCodes.DIMENSION_MISMATCH, 'Inner dimensions must match' );
}
var Result = new Matrix( dimOuterLeft, dimOuterRight );
for( var i = 1; i <= dimOuterLeft; i++ ) {
for( var j = 1; j <= dimOuterRight; j++ ) {
var temp = 0,
rowA = this.__getRow( i ),
columnB = M.__getColumn( j );
for( var k = 0; k < dimInner; k++ ) {
temp += rowA[k] * columnB[k];
}
Result.___set( i, j, temp );
}
}
return Result;
};
/**
* Transpose the matrix, i.e. take the rows as the columns of the resulting matrix.
* @returns {Matrix}
*/
Matrix.prototype.transpose = function () {
var rows = this.rows(),
Result = new Matrix( this.columns(), rows );
for( var i = 1; i <= rows; i++ ) {
Result.__setColumn( i, this.__getRow( i ) );
}
return Result;
};
/**
* Calculate the trace, i.e. the sum of all diagonal entries.
* @returns {number} Sum of diagonal entries.
*/
Matrix.prototype.trace = function () {
if( !this.isSquare() ) {
throw new MatrixError( MatrixError.ErrorCodes.DIMENSION_MISMATCH, 'Matrix must be square' );
}
var rows = this.rows(),
trace = 0;
for( var i = 1; i <= rows; i++ ) {
trace += this.___get( i, i );
}
return trace;
};
/**