WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : Matrix Class (PHP5 and up)
Categories : PHP, PHP Classes, Arrays Click here to Update Your Picture
Exception e
Date : Jul 31st 2005
Grade : 2 of 5 (graded 3 times)
Viewed : 3195
File : No file for this code example.
Images : No Images for this code example.
Search : More code by Exception e
Action : Grade This Code Example
Tools : My Examples List

  Submit your own code examples 
 

<?php
/**
* Basic class for matrix operations
*
*/
class Matrix        {
        
        /**
        * the matrix, a two dimensional array
        * @var array
        */
        private $matrix;

        /**
        * total of rows of the matrix
        * @var int
        */
        private $rowCount = 0;

        /**
        * total of columns of the matrix
        * @var int
        */
        private $columnCount = 0;

        /**
        * Constructs a new Matrix based on the two-dimensional that is passed in
        * @param array $matrix a two-dimensional array. $matrix is passed by reference
                                        and should be indexed without gaps, starting from 0!
                                        the first dimension contains arrays which are the rows
        */
        function __construct(&$matrix)        {
                $this->matrix                =& $matrix;
                $this->rowCount                = count($matrix);
                $this->columnCount        = count(current($matrix));
                //parent::__construct($array);
        }

        /**
        * returns the row of the matrix at position $index
        * if $index is an invalid key of the row, an exception will be thrown
        * @param int $index key of the row that has to be retrieved. possible values ranges from 0 to numberOfRows - 1
        * @return array
        */
        function getRow($index)        {
                if (!array_key_exists($index, $this->matrix))        {
                        throw new Exception('invalid row index provided');
                }
                return $this->matrix[$index];
        }

        /**
        * returns the column of the matrix at position $index
        * if $index is an invalid key of the row, an exception will be thrown
        * @param int $index key of the row that has to be retrieved. possible values ranges from 0 to numberOfRows - 1
        * @return array
        */
        function getColumn($index)        {
                $res = array();

                if ($index > $this->columnCount - 1 || $index < 0)        {
                        throw new Exception('invalid column index provided');
                }
                foreach ($this->matrix as $row)        {
                        $res[] = $row[$index];
                }
                return $res;
        }

        /**
        * multiply $rhs with this Matrix
        * @param mixed $rhs
                        if $rhs is numeric, each value of this matrix is multiplicated by $rhs (so called scalar multiplication)
                        if $rhs is a Matrix, a ordinary matrix product wil be returned
                        see <a href="http://en.wikipedia.org/wiki/Matrix_multiplication">http://en.wikipedia.org/wiki/Matrix_multiplication</a> for a formal explanation
        * @return Matrix new Matrix-object as the result of the operation
        */
        function multiply($rhs)        {
                if (is_numeric($rhs))        {
                        return $this->multiplyByNumber($rhs);
                } elseif ($rhs instanceof Matrix)        {
                        return $this->multiplyByMatrix($rhs);
                } else        {
                        throw new Exception('invalid operand');
                }
        }

        /**
        * sums this and $rhs matrix.
        * The dimensions of the both matrices have to be te same.<br>see <a href="http://en.wikipedia.org/wiki/Matrix_%28mathematics%29#Sum">http://en.wikipedia.org/wiki/Matrix_%28mathematics%29#Sum</a> for a formal explanation
        * @param Matrix $rhs
        * @return Matrix new Matrix-object as the result of the operation
        */
        function sum(Matrix $rhs)        {
                if ($rhs->rowCount !== $this->rowCount && $rhs->columnCount !== $this->columnCount)        {
                        throw new Exception('matrices cannot be added, because they have different dimensions');
                }

                for ($i = 0; $i < $this->rowCount; $i++)        {
                        $res[$i] = array();
                        for ($j = 0; $j < $this->columnCount; $j++)        {
                                $res[$i][$j] = $this->matrix[$i][$j] + $rhs->matrix[$i][$j];
                        }
                }
                return new Matrix($res);
        }

        /**
        * subtracts $rhs from this matrix
        * The dimensions of the both matrices have to be te same. Works like sum(), but this time the operation is subtract<br>
        * @param Matrix $rhs
        * @return Matrix new Matrix-object as the result of the operation
        */
        function minus(Matrix $rhs)        {
                if ($rhs->rowCount !== $this->rowCount && $rhs->columnCount !== $this->columnCount)        {
                        throw new Exception('matrices cannot be subtracted, because they have different dimensions');
                }

                for ($i = 0; $i < $this->rowCount; $i++)        {
                        $res[$i] = array();
                        for ($j = 0; $j < $this->columnCount; $j++)        {
                                $res[$i][$j] = $this->matrix[$i][$j] - $rhs->matrix[$i][$j];
                        }
                }
                return new Matrix($res);
        }

        function numberOfRows()        {
                return $this->rowCount;
        }

        function numberOfColumns()        {
                return $this->columnCount;
        }

        /**
        * HTML representation of the Matrix
        * only for debugging purposes
        * @return string table
        *
        */
        function __toString()        {
                $s = '<table border="1">';
                for ($i = 0; $i < $this->rowCount; $i++)        {
                        $s .= '<tr>';
                        for ($j = 0; $j < $this->columnCount; $j++)        {
                                $s .= '<td>'.$this->matrix[$i][$j].'</td>';
                        }
                        $s .= '</tr>';
                }
                return $s.'</table>';
        }

        private function multiplyByNumber($number)        {
                for ($i = 0; $i < $this->rowCount; $i++)        {
                        $res[$i] = array();
                        for ($j = 0; $j < $this->columnCount; $j++)        {
                                $res[$i][$j] = $this->matrix[$i][$j] * $number;
                        }
                }
                return new Matrix($res);
        }

        private function multiplyByMatrix(Matrix $rhs)        {
                if ($this->columnCount !== $rhs->rowCount)        {
                        throw new Exception('The matrices cannot be multiplied');
                }
                $res = array();

                for ($i = 0; $i < $this->rowCount; $i++)        {
                        $res[$i] = array();
                        for ($j = 0; $j < $rhs->columnCount ; $j++)        {
                                $res[$i][$j] = 0;
                                for ($k = 0; $k < $this->columnCount; $k++)        {
                                        $res[$i][$j] += $this->matrix[$i][$k] * $rhs->matrix[$k][$j];
                                }
                        }
                }
                return new Matrix($res);
        }
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Matrix</title>
</head>
<h1>Example</h1>
<body>
<?php
$a = array(
                array(1,2,3),
                array(1,2,0)
        );
$b = array(
                array(2,4,6),
                array(4,5,4),
                array(1,1,0),
        );


$mA = new Matrix($a);
$mB = new Matrix($b);

$multiply = $mA->multiply($mB);

// what's in it?
echo $multiply->__toString();
echo '<hr>';
echo $mA->multiply(6);
?>
</body>
</html>



Array Insertion
Categories : PHP, PHP Classes, Arrays
PHPDRAW, the php wannabe Photoshop ;-)
Categories : PHP, PHP Classes, GD image library, Arrays
HTML_Graphs uses PHP to provide a consistent interface for creating HTML based charts. The user of the class sets up arrays that are passed to html_graph() which then takes care of all the messy HTML layout.
Categories : Graphics, Arrays, PHP, PHP Classes, Charts and Graphs
Compare two texts and display a block of text with the differences between them.
Categories : PHP, PHP Classes, Filesystem, Strings, Arrays
Sort the results from a SELECT query (any number of columns) into an array automatically.
Categories : PHP, PHP Classes, Arrays, Databases, MySQL
A class to put get and post variables in hidden form elements. Works on scalars, normal arrays, associative arrays.
Categories : Algorithms, Variables, Arrays, PHP, PHP Classes
Tweak Array, insert/add elements to any position of your arrays - delete elements from your arrays - move elements within your arrays - replace elements from your arrays ... the array, 'dynamically' grows or shrinks to whatever we tweak it.
Categories : PHP Classes, Arrays, PHP
XML To Array
Categories : PHP, PHP Classes, XML, Arrays
PHP Script to find url links in a page
Categories : PHP, URLs, Regexps, Arrays
very simple ftp class
Categories : PHP, PHP Classes, FTP
PHP Paypal IPN Integration Class v1.0.0
Categories : PHP, PHP Classes, Payment Gateways
Tag content retrieval from websites with preg_match
Categories : PHP, Regexps, Arrays, HTML and PHP
Array values from javascript to php
Categories : PHP, Java Script, Arrays
A Timing Class
Categories : PHP, PHP Classes, Date Time
The class to check load time of your script VERY usefull for relatively slow applications, but not only..
Categories : PHP, PHP Classes, Debugging
 Shea Sollars wrote : 1339
VERY nice.
 
 Joost Langen wrote : 1341
I tried to test your script, but did`t succeed. this is the error: 
" Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or `}` in /home/resellers/841289/841289/josefem.nl/www/test/matrix.php on line 12 "
I can`t see what`s wrong.
gr Joost
 
 Exception e wrote :1342
In response to Joost Langen I`ve sent a private message, but I realised that more people can have the same problem as Joost has.
Therefore, I repeat my answer here: I think that your php version is too low. In order to run this code you need at  least PHP5.
If you want to check your php version, just have a look at php_info or simply call &lt;?php echo `my php version is: `.PHP_VERSION; ?&gt;
In order to run this code under PHP4, you should strip of the `private` keywords and replace the exceptions with errors. For example:
trigger_error(`invalid row index provided`, E_USER_ERROR);
But I like to encourage the use of PHP5... :)