130. PHP Program to find Subtraction of two matrices.
How does this program work?
- In this program we are going to learn about how to find Subtraction of two matrices using PHP.
- If rows and columns of given two matrices are same then only subtraction will be possible. Otherwise It is not possible to subtract a 2 × 3 matrix with a 3 × 2 matrix.
- Subtraction can be performed by corresponding their elements then result will be displayed on matrix format.
Here is the code
<html>
<head>
<title>PHP Program for Subtraction of two matrices</title>
</head>
<body>
<?php
// Elements of matrix a
$a = array
(
array(1, 0, 8),
array(4, 5, 6),
array(1, 9, 2)
);
//Elements of matrix b
$b = array
(
array(1, 1, 1),
array(2, 3, 1),
array(1, 5, 1)
);
// To determine the no.of rows and columns of given matrix
$rows = count($a);
$cols = count($a[0]);
//Performs subtraction of matrices a and b. Store the result in matrix diff
for($i = 0; $i < $rows; $i++)
{
for($j = 0; $j < $cols; $j++) {
$diff[$i][$j] =0; //Initially diff to be declare with 0
$diff[$i][$j] = $a[$i][$j] - $b[$i][$j];
}
}
echo ("Subtraction of two matrices: </br>");
// To print result in matrix form
for($i = 0; $i < $rows; $i++) {
for($j = 0; $j < $cols; $j++) {
echo($diff[$i][$j] . " ");
echo " ";
}
echo("<br>" );
}
?>
</body>
</html>