-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmatrix.php
841 lines (718 loc) · 15.9 KB
/
matrix.php
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
<?php
/**
* Class Matrix
*/
require_once 'matrix_algorithms.php';
require_once 'matrix_factory.php';
class Matrix
{
/**
* @var array - matrix container
*/
protected $matrix;
/**
* Construct matrix from array of clone matrix
*
* @param array|Matrix $data
*/
public function __construct(&$data)
{
if (Matrix::isMatrix($data)) {
return self::fromArray($data->getArray());
}
return self::fromArray($data);
}
/**
* Construct matrix from array
*
* @param array $array
* @throws InvalidArgumentException
*/
protected function fromArray(&$array)
{
if (!is_array($array)) {
throw new InvalidArgumentException('Array needed. Given' . gettype($array));
}
// Если вектор-строка
if (!is_array($array[0])) {
$array = array($array);
}
$rows = count($array);
$cols = count($array[0]);
for ($row = 1; $row < $rows; $row++) {
if ($cols !== count($array[$row])) {
throw new InvalidArgumentException('Array has different rows');
}
}
$matrix = array();
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
$matrix[$i][$j] = (float) $array[$i][$j];
}
}
$this->matrix = $matrix;
}
///
/**
* Return array-container of matrix
*
* @return array
*/
public function getArray()
{
return $this->matrix;
}
/**
* Return element
*
* @param $row
* @param $col
* @return number
* @throws OutOfRangeException
*/
public function getElem($row, $col)
{
list($rows, $cols) = $this->getSize();
if ($row < $rows && $col < $cols) {
return $this->matrix[$row][$col];
} else {
throw new OutOfRangeException("Invalid offset. row = $row must be lover $rows; col = $col must be lover $cols;");
}
}
/**
* Set element of matrix
*
* @param $row
* @param $col
* @param number $value
* @return array
* @throws OutOfRangeException
*/
public function setElem($row, $col, $value)
{
list($rows, $cols) = $this->getSize();
if ($row < $rows && $col < $cols) {
return $this->matrix[$row][$col] = (float) $value;
} else {
throw new OutOfRangeException("Invalid offset. row = $row must be lower $rows; col = $col must be lower $cols");
}
}
/**
* Return column
*
* @param $col
* @param bool $return_array
* @return array|Matrix
* @throws OutOfRangeException
*/
public function getColumn($col, $return_array = false)
{
list($rows, $cols) = $this->getSize();
if ($col >= $cols) {
throw new OutOfRangeException("Invalid offset. col = $col must be lower $cols");
}
$res = array();
for ($row = 0; $row < $rows; $row++) {
$res[$row] = $this->getElem($row, $col);
}
if ($return_array) {
return $res;
} else {
$res = new Matrix($res);
return $res->T();
}
}
/**
* Return this matrix with setted column
*
* @param int $col
* @param Matrix $value
* @return Matrix
* @throws InvalidArgumentException|OutOfRangeException
*/
public function setColumn($col, $value)
{
if (!Matrix::isMatrix($value)) {
throw new InvalidArgumentException('Argument $value must be matrix. '
. gettype($value) . ' given');
}
if (($rows = $this->getRowsCount()) !== $value->getRowsCount()
|| $value->getColsCount() !== 1) {
throw new OutOfRangeException("Count of rows must equals");
}
for ($row = 0; $row < $rows; $row++) {
$this->setElem($row, $col, $value->getElem($row, 0));
}
return $this;
}
/**
* Return row
*
* @param $row
* @param bool $return_array
* @return array|Matrix
* @throws OutOfRangeException
*/
public function getRow($row, $return_array = false)
{
list($rows, $cols) = $this->getSize();
if ($row >= $rows) {
throw new OutOfRangeException("Invalid offset. row = $row must be lower $rows");
}
$res = array();
for ($col = 0; $col < $cols; $col++) {
$res[$col] = $this->getElem($row, $col);
}
return $return_array ? $res : new Matrix($res);
}
// TODO : asd
/**
* @param int $row
* @param Matrix $value
* @return Matrix
* @throws OutOfRangeException
* @throws InvalidArgumentException
*/
public function setRow($row, $value)
{
if (!Matrix::isMatrix($value)) {
throw new InvalidArgumentException('Argument $value must be matrix. '
. gettype($value) . ' given');
}
if (($cols = $this->getColsCount()) !== $value->getColsCount()
|| $value->getRowsCount() !== 1) {
throw new OutOfRangeException("Count of cols must equals");
}
for ($col = 0; $col < $cols; $col++) {
$this->setElem($row, $col, $value->getElem(0, $col));
}
return $this;
}
/**
* Return main diagonal
*
* @param bool $return_array - вернуть массивом
* @return array|Matrix
*/
public function getDiagonal($return_array = false)
{
$diagonal = array();
$matrix = $this->getArray();
$size = $this->getSize();
$n = min($size);
for ($i = 0; $i < $n; $i++) {
$diagonal[$i] = $matrix[$i][$i];
}
return $return_array ? $diagonal : new Matrix($diagonal);
}
/**
* Return size of matrix
*
* @return array($rows, $cols)
*/
public function getSize()
{
$rows = count($this->matrix);
$cols = count($this->matrix[0]);
return array($rows, $cols);
}
/**
* Return rows count
*
* @return int
*/
public function getRowsCount()
{
return count($this->matrix);
}
/**
* Return columns count
*
* @return int
*/
public function getColsCount()
{
return count($this->matrix[0]);
}
///
// TODO : Проверки
/**
* Return matrix with swapped columns
*
* @param int $col1
* @param int $col2
* @return Matrix
* @throws OutOfRangeException
*/
public function swapColumns($col1, $col2)
{
$cols = $this->getColsCount();
if ($col1 >= $cols || $col2 >= $cols) {
throw new OutOfRangeException("Cols $col1, $col2 must be lower than $cols");
}
$col1_value = $this->getColumn($col1);
$col2_value = $this->getColumn($col2);
$new_matrix = clone $this;
$new_matrix->setColumn($col1, $col2_value);
$new_matrix->setColumn($col2, $col1_value);
return $new_matrix;
}
public function swapRows($row1, $row2)
{
list($this->matrix[$row1], $this->matrix[$row2]) =
array($this->matrix[$row2], $this->matrix[$row1]);
}
/**
* Insert column
*
* @param int $pos
* @param Matrix $value
* @return Matrix
* @throws OutOfRangeException
* @throws InvalidArgumentException
*/
public function insertColumn($pos, $value)
{
if (!Matrix::isMatrix($value)) {
throw new InvalidArgumentException('Argument $value must be matrix. '
. gettype($value) . ' given');
}
if (($rows = $this->getRowsCount()) !== $value->getRowsCount()
|| $value->getColsCount() !== 1) {
throw new OutOfRangeException("Count of rows must equals");
}
for ($row = 0; $row < $rows; $row++) {
array_splice($this->matrix[$row], $pos, 0, $value->getElem($row, 0));
}
return $this;
}
/**
* Insert row
*
* @param int $pos
* @param Matrix $value
* @return Matrix
* @throws OutOfRangeException
* @throws InvalidArgumentException
*/
public function insertRow($pos, $value)
{
if (!Matrix::isMatrix($value)) {
throw new InvalidArgumentException('Argument $value must be matrix. '
. gettype($value) . ' given');
}
if (($cols = $this->getColsCount()) !== $value->getColsCount()
|| $value->getRowsCount() !== 1) {
throw new OutOfRangeException("Count of cols must equals");
}
array_splice($this->matrix, $pos, 0, array($value->getRow(0, true)));
return $this;
}
/**
* Return matrix with deleted column
*
* @param int $col
* @return Matrix
* @throws OutOfRangeException
*/
public function deleteColumn($col)
{
$cols = $this->getColsCount();
if ($col >= $cols) {
throw new OutOfRangeException("Invalid offset. col = $col must be lower $cols");
}
foreach ($this->matrix as &$row) {
array_splice($row, $col, 1);
}
return $this;
}
/**
* Return matrix with deleted row
*
* @param int $row
* @return Matrix
* @throws OutOfRangeException
*/
public function deleteRow($row)
{
$rows = $this->getRowsCount();
if ($row >= $rows) {
throw new OutOfRangeException("Invalid offset. row = $row must be lower $rows");
}
array_splice($this->matrix, $row, 1);
return $this;
}
/**
* Swap row and col
*
* @param $row
* @param $col
* @return $this
* @throws OutOfRangeException
* @throws InvalidArgumentException
*/
function swapRowCol($row, $col)
{
if (!$this->isSquare()) {
throw new InvalidArgumentException("Matrix must be square");
}
if ($row != $col) {
throw new InvalidArgumentException("row = $row must be equal col = $col");
}
list($rows, $cols) = $this->getSize();
if ($row >= $rows) {
throw new OutOfRangeException("Invalid offset. row = $row must be lower $rows");
}
if ($col >= $cols) {
throw new OutOfRangeException("Invalid offset. col = $col must be lower $cols");
}
for ($i = 0; $i < $cols; $i++) {
$tmp = $this->matrix[$row][$i];
$this->matrix[$row][$i] = $this->matrix[$i][$col];
$this->matrix[$i][$col] = $tmp;
}
return $this;
}
/// Matrix operations
/**
* Return transposed matrix
*
* @return Matrix
*/
public function T()
{
return MatrixAlgorithms::transpose($this);
}
/**
* Return determinant of matrix
*
* @return number
*/
public function det()
{
return MatrixAlgorithms::determinant($this);
}
/**
* Return inverse matrix
*
* @return Matrix
*/
public function invert()
{
return MatrixAlgorithms::inverseMatrix($this);
}
/**
* Return Euclidean norm
*
* @return number
*/
public function EuclideanNorm()
{
return MatrixAlgorithms::pNorm($this, 2);
}
/**
* Return sum of elements on main diagonal
*
* @return number
*/
public function trace()
{
return array_sum($this->getDiagonal(true));
}
/**
* Return product of elements on main diagonal
*
* @return number
*/
public function prodTrace()
{
return array_product($this->getDiagonal(true));
}
/**
* Return rounded matrix
*
* @param int $decimals
* @return Matrix
*/
public function round($decimals = 0)
{
$callback = function ($elem) use ($decimals) {
return round($elem, $decimals);
};
return $this->map($callback);
}
// Binary operations
/**
* Return sum of matrices
*
* @param Matrix $B
* @return Matrix
* @throws InvalidArgumentException
*/
public function add($B)
{
return $this->elemBinaryOperation($B, function($a, $b){return $a + $b;});
}
/**
* Return sum of matrices
*
* @param Matrix $B
* @return Matrix
* @throws InvalidArgumentException
*/
public function sub($B)
{
return $this->elemBinaryOperation($B, function($a, $b){return $a - $b;});
}
/**
* Return product of elements
*
* @param Matrix $B
* @return Matrix
*/
public function elemProd($B)
{
return $this->elemBinaryOperation($B, function($a, $b){return $a * $b;});
}
/**
* Return division of elements
*
* @param Matrix $B
* @return Matrix
*/
public function elemDiv($B)
{
return $this->elemBinaryOperation($B, function($a, $b){return $a / $b;});
}
/**
* Return matrix applied $operation
*
* @param Matrix $B
* @param $operation
* @return Matrix
* @throws InvalidArgumentException
*/
public function elemBinaryOperation(&$B, $operation)
{
if (!Matrix::isMatrix($B)) {
throw new InvalidArgumentException('Matrix needed. Given' . gettype($B));
}
list($rows, $cols) = $this->getSize();
if (array($rows, $cols) !== $B->getSize()) {
throw new InvalidArgumentException('Invalid size of matrices');
}
$res = MatrixFactory::zeroMatrix($rows, $cols);
for ($row = 0; $row < $rows; $row++) {
for ($col = 0; $col < $cols; $col++) {
$temp = $operation($this->getElem($row, $col), $B->getElem($row, $col));
$res->setElem($row, $col, $temp);
}
}
return $res;
}
/**
* Return product of matrices
*
* @param Matrix|number $B
* @return Matrix
* @throws InvalidArgumentException
*/
public function prod($B)
{
// Умножение на число
if (is_numeric($B)) {
list($rows, $cols) = $this->getSize();
$new_matrix = MatrixFactory::zeroMatrix($rows, $cols);
for ($row = 0; $row < $rows; $row++) {
for ($col = 0; $col < $cols; $col++) {
$temp = $this->getElem($row, $col) * $B;
$new_matrix->setElem($row, $col, $temp);
}
}
return $new_matrix;
}
if (!Matrix::isMatrix($B)) {
throw new InvalidArgumentException("Argument must be Matrix or number");
}
list($rows1, $cols1) = $this->getSize();
list($rows2, $cols2) = $B->getSize();
if ($cols1 !== $rows2) {
throw new InvalidArgumentException("Invalid size of matrices");
}
$new_matrix = MatrixFactory::zeroMatrix($rows1, $cols2);
for ($row = 0; $row < $rows1; $row++) {
for ($col = 0; $col < $cols2; $col++) {
$sum = 0;
for ($k = 0; $k < $cols1; $k++) {
$sum += $this->getElem($row, $k) * $B->getElem($k, $col);
}
$new_matrix->setElem($row, $col, $sum);
}
}
return $new_matrix;
}
/**
* Return $this * $B^-1
*
* @param Matrix $B
* @return Matrix
*/
public function div($B)
{
return $this->prod($B->invert());
}
/// Utils
/**
* Return true if matrices is equals
*
* @param Matrix $matrix
* @param float $eps
* @return bool
* @throws InvalidArgumentException
*/
public function equals($matrix, $eps = 0.0)
{
if (!Matrix::isMatrix($matrix)) {
throw new InvalidArgumentException('Matrix needed. Given' . gettype($matrix));
}
if ($eps === 0) {
return $this->getArray() == $matrix->getArray();
} else {
$sub = $this->sub($matrix);
return $sub->EuclideanNorm() < $eps;
}
}
/**
* Return is matrix
*
* @static
* @param $matrix
* @return bool
*/
public static function isMatrix($matrix)
{
return is_a($matrix, __CLASS__);
}
/**
* Return is square
*
* @return bool
*/
public function isSquare()
{
list($rows, $cols) = $this->getSize();
return $rows === $cols;
}
// TODO : max, min, sort, etc.
/**
* Return true if elems return true from $callback, false else
*
* @param $callback
* @return bool
*/
public function all($callback)
{
list($rows, $cols) = $this->getSize();
for ($row = 0; $row < $rows; $row++) {
for ($col = 0; $col < $cols; $col++) {
if (!$callback($this->getElem($row, $col))) {
return false;
}
}
}
return true;
}
/**
* Map for matrix
*
* @param $callback
* @return Matrix
*/
public function map($callback)
{
$res = clone $this;
list($rows, $cols) = $res->getSize();
for ($row = 0; $row < $rows; $row++) {
for ($col = 0; $col < $cols; $col++) {
$temp = $callback($res->getElem($row, $col));
$res->setElem($row, $col, $temp);
}
}
return $res;
}
/**
* Return abs matrix
*
* @return Matrix
*/
public function abs()
{
$callback = function ($elem) {
return abs($elem);
};
return $this->map($callback);
}
/**
* Reduce for matrix
*
* @param $callback
* @param float $initial
* @return number
*/
public function reduce($callback, $initial = 0.0)
{
$rows = $this->getRowsCount();
for ($row = 0; $row < $rows; $row++) {
$initial = array_reduce($this->getRow($row, true), $callback, $initial);
}
return $initial;
}
/**
* Return sum of all elements
*
* @return number
*/
public function sumAll()
{
$callback = function($sum, $elem) {
return $sum + $elem;
};
return $this->reduce($callback);
}
/**
* Return product of elements of matrix
*
* @return number
*/
public function prodAll()
{
$callback = function($acc, $elem) {
return $acc * $elem;
};
return $this->reduce($callback, 1);
}
/**
* Return string representation of matrix
*
* @param string $col_div
* @param string $row_div
* @return string
*/
public function toString($col_div = ", ", $row_div = ";\n")
{
$rows_arr = array();
$rows = $this->getRowsCount();
for ($i = 0; $i < $rows; $i++) {
$rows_arr[] = implode($col_div, $this->getRow($i, true));
}
return implode($row_div, $rows_arr);
}
/**
* Return string representation of matrix
* @return string
*/
public function __toString()
{
return $this->toString();
}
}