Practical - 4 IWD

 AIM : Write a script to perform 3x3 matrix Multiplication.

3×3 Matrix Multiplication using PHP

📌 Theory (For Exam)

  • Matrix multiplication is possible only if
    Number of columns of Matrix A = Number of rows of Matrix B

  • For 3×3 matrices, the result is also a 3×3 matrix

  • Formula used:

C[i][j]=k=02A[i][k]×B[k][j]C[i][j] = \sum_{k=0}^{2} A[i][k] \times B[k][j]


✅ PHP Script for 3×3 Matrix Multiplication

<?php // Define first 3x3 matrix $A = array( array(1, 2, 3), array(4, 5, 6), array(7, 8, 9) ); // Define second 3x3 matrix $B = array( array(9, 8, 7), array(6, 5, 4), array(3, 2, 1) ); // Initialize result matrix with zeros $result = array( array(0, 0, 0), array(0, 0, 0), array(0, 0, 0) ); // Matrix multiplication logic for ($i = 0; $i < 3; $i++) { for ($j = 0; $j < 3; $j++) { for ($k = 0; $k < 3; $k++) { $result[$i][$j] += $A[$i][$k] * $B[$k][$j]; } } } ?> <!DOCTYPE html> <html> <head> <title>3x3 Matrix Multiplication</title> <style> table { border-collapse: collapse; margin: 10px; } td { border: 1px solid black; padding: 8px; text-align: center; } </style> </head> <body> <h2>Matrix A</h2> <table> <?php for ($i = 0; $i < 3; $i++) { echo "<tr>"; for ($j = 0; $j < 3; $j++) { echo "<td>{$A[$i][$j]}</td>"; } echo "</tr>"; } ?> </table> <h2>Matrix B</h2> <table> <?php for ($i = 0; $i < 3; $i++) { echo "<tr>"; for ($j = 0; $j < 3; $j++) { echo "<td>{$B[$i][$j]}</td>"; } echo "</tr>"; } ?> </table> <h2>Resultant Matrix (A × B)</h2> <table> <?php for ($i = 0; $i < 3; $i++) { echo "<tr>"; for ($j = 0; $j < 3; $j++) { echo "<td>{$result[$i][$j]}</td>"; } echo "</tr>"; } ?> </table> </body> </html>

🧠 Step-by-Step Explanation

1️⃣ Matrix Declaration

$A = array(...); $B = array(...);
  • Two 3×3 matrices are defined using 2D arrays


2️⃣ Result Matrix Initialization

$result = array( array(0,0,0), array(0,0,0), array(0,0,0) );
  • Stores the final multiplication result


3️⃣ Matrix Multiplication Logic

for ($i = 0; $i < 3; $i++) for ($j = 0; $j < 3; $j++) for ($k = 0; $k < 3; $k++) $result[$i][$j] += $A[$i][$k] * $B[$k][$j];
  • Outer loop ($i) → Row of Matrix A

  • Middle loop ($j) → Column of Matrix B

  • Inner loop ($k) → Performs multiplication and addition


📊 Sample Output

Matrix A Matrix B Result (A × B) 1 2 3 9 8 7 30 24 18 4 5 6 6 5 4 84 69 54 7 8 9 3 2 1 138 114 90

🎓 Viva / Exam Questions

Q1. Why three loops are used?
👉 To traverse rows, columns, and perform multiplication.

Q2. Condition for matrix multiplication?
👉 Columns of first matrix = Rows of second matrix.

Q3. Data structure used?
👉 Two-dimensional array.

Q4. Size of resultant matrix?
👉 Same as rows of first matrix × columns of second matrix.

Comments

Popular posts from this blog

Unit I - Introduction to PHP

Practical - 1 IWD

Practical - 10 IWD