/** * Multiply Matrices * * This function will multiply the current matrix with the matrix provided. * If current Matrix is denoted by 'A' and the inputted is denoted by 'B', * When written, this will return AB. * * @link http://en.wikipedia.org/wiki/Matrix_multiplication * @param Matrix $bMatrix The matrix to multiply with the current * @return Matrix The result of multiplication. * @throws \Exception $msg explains why operation failed */ public function mpMatrix(Matrix $bMatrix) { if (!$this->_verify() || !$bMatrix->_verify()) { $eM1 = $this->toString(); $eM2 = $bMatrix->toString(); throw new \Exception("Either '{$eM1}' and/or '{$eM2}' is not a valid Matrix", Matrix::E_INVALID_MATRIX); } $aArray = $this->matrix; $bArray = $bMatrix->getArray(); //The number of columns in A must match the number of rows in B if (count($aArray[0]) != count($bArray)) { $mA = $this->toString(); $mB = $bMatrix->toString(); throw new \Exception("Columns in '{$mA}' don't match Rows of '{$mB}'", Matrix::E_NOT_EQUAL); } $rArray = array(); //Loop through rows of Matrix A for ($i = 0; $i < count($aArray); $i++) { //Loop through the columns of Matrix B for ($j = 0; $j < count($bArray[0]); $j++) { $value = 0; //loop through the rows of Matrix B for ($k = 0; $k < count($bArray); $k++) { $value += $aArray[$i][$k] * $bArray[$k][$j]; } $rArray[$i][$j] = $value; } } $rMatrix = new Matrix($this->toString($rArray)); return $rMatrix; }