Skip to content

Commit 4911712

Browse files
committed
Added trace feature to Matrix Class
See #10
1 parent 6a33924 commit 4911712

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/Malenki/Math/Matrix.php

+18-1
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ public function __get($name)
104104
return $this->isSquare();
105105
}
106106

107-
if(in_array($name, array('cofactor', 'adjugate', 'inverse', 'det', 'determinant', 'transpose')))
107+
if(in_array($name, array('cofactor', 'adjugate', 'inverse', 'det', 'trace', 'determinant', 'transpose')))
108108
{
109109
return $this->$name();
110110
}
@@ -691,6 +691,23 @@ public function det()
691691
}
692692
}
693693

694+
public function trace()
695+
{
696+
if(!$this->isSquare())
697+
{
698+
throw new \RuntimeException('Cannot compute trace of non square matrix!');
699+
}
700+
701+
$int = 0;
702+
703+
for($i = 0; $i < $this->size->rows; $i++)
704+
{
705+
$int += $this->get($i, $i);
706+
}
707+
708+
return $int;
709+
}
710+
694711

695712
public function determinant()
696713
{

tests/MatrixTest.php

+19
Original file line numberDiff line numberDiff line change
@@ -311,4 +311,23 @@ public function testToString()
311311
$this->assertEquals("1 2+i 3\n4 5 60", sprintf('%s', $m));
312312
}
313313

314+
public function testGettingTraceShouldSuccess()
315+
{
316+
$m = new Matrix(2, 2);
317+
$m->populate(array(1, 2, 3, 4));
318+
319+
$this->assertEquals(5, $m->trace());
320+
$this->assertEquals(5, $m->trace);
321+
}
322+
323+
/**
324+
* @expectedException \RuntimeException
325+
*/
326+
public function testGettingTraceiFromNonSquareMatrixShouldFail()
327+
{
328+
$m = new Matrix(2, 3);
329+
$m->populate(array(1, 2, 3, 4, 5, 6));
330+
331+
$m->trace();
332+
}
314333
}

0 commit comments

Comments
 (0)