Add Matrices

This algorithm computes the sum of two matrices.



									class Matrix
{
	public $_Matrix;
	public $Rows;
	public $Columns;
}

function AddMatrices($firstMatrix, $secondMatrix)
{
	$retVal = new Matrix();
	
	if ($firstMatrix->Rows == $secondMatrix->Rows && $firstMatrix->Columns == $secondMatrix->Columns)
	{
		$sum = array();

		for ($i = 0; $i < $firstMatrix->Rows; $i++)
		{
			for ($j = 0; $j < $firstMatrix->Columns; $j++)
			{
				$sum[$i][$j] = $firstMatrix->_Matrix[$i][$j] + $secondMatrix->_Matrix[$i][$j];
			}
		}

		$retVal->_Matrix = $sum;
		$retVal->Rows = $firstMatrix->Rows;
		$retVal->Columns = $firstMatrix->Columns;
		return $retVal;
	}

	return $retVal;
}
								


Example

									$m1 = array();
$m1[0][0] = 1;
$m1[0][1] = 2;
$m1[1][0] = 3;
$m1[1][1] = 4;

$m2 = array();
$m2[0][0] = 5;
$m2[0][1] = 6;
$m2[1][0] = 2;
$m2[1][1] = 1;

$matrix1 = new Matrix();
$matrix1->_Matrix = $m1;
$matrix1->Rows = 2;
$matrix1->Columns = 2;

$matrix2 = new Matrix();
$matrix2->_Matrix = $m2;
$matrix2->Rows = 2;
$matrix2->Columns = 2;

$sumMatrix = AddMatrices($matrix1, $matrix2);
								


Output

									[0][0] = 6
[0][1] = 8
[1][0] = 5
[1][1] = 5