Practical-09
Write a PHP program to generate the multiplication of matrix.
Introduction
Matrix multiplication is an important calculation that is often used to solve real-world problems in mathematical and computer science contexts. By multiplying two matrices together, it is possible to work out the value of one matrix based on the values of other matrix. This process allows the manipulation of data and the solving of equations by creating a new matrix from multiplying matrices. The basic unit of calculation in matrix multiplication is the element, which is the smallest value of a matrix. The result of a successful matrix multiplication will be a new matrix with the same number of rows as the first matrix and the same number of columns as the second matrix.
In PHP, matrix multiplication can be completed with a complex combination of loops, various array functions, and mathematical operations. PHP provides a range of functions to make it easier to work with matrices, including functions for both element-wise mathematical operations and functions to create loops and arrays of data. The code must include an array that houses the matrix, a loop that iterates over the array, and a mathematical operation that multiplies the elements of the two matrices.
Code
<?php
//define our two matrices
$matrix1 = array(
array(2, 3),
array(4, 5)
);
$matrix2 = array(
array(6, 7),
array(8, 9)
);
// calculate our result matrix
$result = array();
for($i=0; $i<=1; $i++){
for($j=0; $j<=1; $j++){
$result[$i][$j] = 0;
for($k=0; $k<=1; $k++){
$result[$i][$j] += $matrix1[$i][$k] * $matrix2[$k][$j];
}
}
}
//display our result
echo "<p>Result of Matrix Multiplication : </p>";
echo "<pre/>";print_r($result);
?>
Output
Result of Matrix Multiplication :
Array
(
[0] => Array
(
[0] => 36
[1] => 42
)
[1] => Array
(
[0] => 48
[1] => 54
)
)
This code creates two matrices and assigns the values from the two matrices to the result matrix. It then creates a loop that iterates over the two matrices and performs the mathematical multiplication of the elements in the matrices. The result is then printed.