cvs: pear /Math_Matrix Matrix.php
| From: | Jesus M. Castagnetto | Date: | Tue, 28 May 2002 09:12:54 +0000 |
| Subject: | cvs: pear /Math_Matrix Matrix.php | ||
| Groups: | php.pear.cvs | ||
| Request: | Send a blank email to pear-cvs+get-4198@lists.php.net to get a copy of this message | ||
jmcastagnetto Tue May 28 05:12:54 2002 EDT
Modified files:
/pear/Math_Matrix Matrix.php
Log:
Added recursive methods for calculation of determinant for N x N matrices
Index: pear/Math_Matrix/Matrix.php
diff -u pear/Math_Matrix/Matrix.php:1.2 pear/Math_Matrix/Matrix.php:1.3
--- pear/Math_Matrix/Matrix.php:1.2 Fri May 24 14:35:14 2002
+++ pear/Math_Matrix/Matrix.php Tue May 28 05:12:53 2002
@@ -18,7 +18,7 @@
//
// Matrix definition and manipulation package
//
-// $Id: Matrix.php,v 1.2 2002/05/24 18:35:14 jmcastagnetto Exp $
+// $Id: Matrix.php,v 1.3 2002/05/28 09:12:53 jmcastagnetto Exp $
//
require_once 'PEAR.php';
@@ -175,14 +175,14 @@
* @access public
* @return mixed an array of integers on success, a PEAR_Error object otherwise
*/
- function getSize() {
+ function getSize() {/*{{{*/
if ($this->isEmpty())
return PEAR::raiseError('Matrix has not been populated');
else
return array($this->_num_rows, $this->_num_cols);
- }
+ }/*}}}*/
- function setElement($row, $col, $value) {
+ function setElement($row, $col, $value) {/*{{{*/
if ($this->isEmpty())
return PEAR::raiseError('Matrix has not been populated');
if ($row >= $this->_num_rows && $col >= $this->_num_cols)
@@ -191,14 +191,49 @@
return PEAR::raiseError('Incorrect value, expecting a number');
$this->_data[$row][$col] = $value;
return true;
- }
+ }/*}}}*/
- function getElement($row, $col) {
+ function getElement($row, $col) {/*{{{*/
if ($this->isEmpty())
return PEAR::raiseError('Matrix has not been populated');
if ($row >= $this->_num_rows && $col >= $this->_num_cols)
return PEAR::raiseError('Incorrect row and column values');
return $this->_data[$row][$col];
+ }/*}}}*/
+
+ function determinant() {
+ if ($this->isEmpty())
+ return PEAR::raiseError('Matrix has not been populated');
+ if (!$this->isSquare())
+ return PEAR::raiseError('Determinant undefined for non-square matrices');
+ return _calcDet($arr);
+ }
+
+ function _calcDet($arr) {
+ $n = count($arr);
+ $sum = 0;
+ $tarr = array();
+ if ($n == 1)
+ return $arr[0][0];
+ else if ($n == 2)
+ return ($arr[0][0] * $arr[1][1] -
+ $arr[1][0] * $arr[0][1]);
+ else
+ for ($i=0; $i < $n; $i++) {
+ if ($arr[0][$i] != 0)
+ for ($j=1; $j < $n; $j++)
+ for ($k=2; $k < $n; $k++)
+ if ($k > $i)
+ $tarr[$j - 1][$k - 1] = $arr[$j][$k];
+ else if ($k < $i)
+ $tarr[$j - 1][$k] = $arr[$j][$k];
+ $factor = $arr[1][$i] * $this->_calcDet($tarr);
+ if ($i % 2 == 0)
+ $sum -= $factor;
+ else
+ $sum += $factor;
+ }
+ return sum;
}
function getRow ($row) {/*{{{*/