Skip to main content

Multiplication of two matrix in php

matrix multiplication formula

Php program for Multiplication of two matrix. Here more solutions.

<?php
/*
  Php program for
  Two matrix multiplication
*/
class Multiply
{
	// Display the element of given 2d matrix
	public static function printRecord($matrix)
	{
		echo "  --------------\n";
		// Assume  N x N Matrix size
		$row = count($matrix);
		$col = count($matrix[0]);
		// Iterate the row element
		for ($i = 0; $i < $row; ++$i)
		{
			// Iterate the column element
			for ($j = 0; $j < $col; ++$j)
			{
				// Display element value
				echo "  ".($matrix[$i][$j]);
			}
			// Add new line
			print("\n");
		}
		print("\n");
	}
	public static
	function multiplication($a, $b)
	{
		// Get the size
		$row = count($a);
		$col = count($a[0]);
		// This matrix are store the result of multiplication 
		$result = array_fill(0, $row, array_fill(0, $col, 0));
		for ($i = 0; $i < $row; ++$i)
		{
			for ($j = 0; $j < $col; ++$j)
			{
				// Set the initial value of new matrix element
				$result[$i][$j] = 0;
				for ($k = 0; $k < $row; ++$k)
				{
					// Multiply matrix A [i] row and [k] columns to 
					// the Matrix B [k] columns and [j] rows.
					$result[$i][$j] += $a[$i][$k] * $b[$k][$j];
				}
			}
		}
		echo "  Matrix A\n";
		// Print element of matrix x
		Multiply::printRecord($a);
		echo "  Matrix B\n";
		// Print element of matrix y
		Multiply::printRecord($b);
		echo "  Matrix [(A) x (B)]\n";
		// Display resultant matrix
		Multiply::printRecord($result);
	}
	public static function main()
	{
		// Define matrix A
		$a = array(
          array(1, 2, 3), 
          array(6, 1, 2), 
          array(5, 4, 3)
        );
		// Define matrix B
		$b = array(
          array(3, 1, 3), 
          array(1, 1, 2), 
          array(2, 2, 3)
        );
		Multiply::multiplication($a, $b);
	}
}
Multiply::main();

Output

  Matrix A
  --------------
  1  2  3
  6  1  2
  5  4  3

  Matrix B
  --------------
  3  1  3
  1  1  2
  2  2  3

  Matrix [(A) x (B)]
  --------------
  11  9  16
  23  11  26
  25  15  32





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment