Subtract Matrices

This algorithm finds difference between corresponding elements of two matrices.



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

function SubtractMatrices($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] = 8;
$m1[0][1] = 6;
$m1[1][0] = 7;
$m1[1][1] = 5;

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

$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 = SubtractMatrices($matrix1, $matrix2);
								


Output

									[0][0] = 4
[0][1] = 3
[1][0] = 2
[1][1] = 3