Skip to content

Commit 010b528

Browse files
committed
Implemented matrix rank
1 parent a69e54e commit 010b528

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/Matrix.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,29 @@ public function det() : float
645645
return (-1.) ** $swaps * $dHat;
646646
}
647647

648+
/**
649+
* Calculate the rank of the matrix i.e the number of pivots
650+
* in its reduced row echelon form.
651+
*
652+
* @return int
653+
*/
654+
public function rank() : int
655+
{
656+
$pivots = 0;
657+
658+
foreach ($this->rref() as $row) {
659+
foreach ($row as $value) {
660+
if ($value != 0) {
661+
$pivots++;
662+
663+
continue 2;
664+
}
665+
}
666+
}
667+
668+
return $pivots;
669+
}
670+
648671
/**
649672
* Return the elementwise reciprocal of the matrix.
650673
*

tests/MatrixTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,13 @@ public function test_det()
350350
$this->assertEquals(-544., $this->c->det());
351351
}
352352

353+
public function test_rank()
354+
{
355+
$this->assertEquals(3, $this->a->rank());
356+
$this->assertEquals(1, $this->b->rank());
357+
$this->assertEquals(3, $this->c->rank());
358+
}
359+
353360
public function test_reciprocal()
354361
{
355362
$z = $this->a->reciprocal();

0 commit comments

Comments
 (0)