Open In App

How to Calculate Determinant of a Matrix in PHP?

Last Updated : 13 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Matrix of size M*N, where N and M is an Integer, we need to Calculate calculate of a Matrix in PHP.

Example:

Input: [[1, 2],[2, 3]]
Output: 6
Explanation: (1*3)-(2*2)= 6-4= 2

There are several ways to find the determinant of the matrix in PHP which are as follows:

Using Recursion

In this approach, we use recursion to calculate the determinant by expanding along the first row. For each element in the first row, it multiplies the element by the determinant of the submatrix that remains after removing the row and column of that element.

  • If the matrix is 2x2, directly compute the determinant using the formula.
  • For matrices larger than 2x2, expand the determinant along the first row.
  • For each element in the first row, calculate the determinant of the submatrix formed by removing the current row and column of the element.
  • Multiply the element by the determinant of its submatrix and apply the alternating sign (positive for even index, negative for odd index).
  • Sum these values to get the determinant.

Example: The below code example implements recursion in PHP to find determinant of a matrix.

PHP
<?php
// Function to calculate the determinant of a matrix
function determinant($matrix) {
    $n = count($matrix);

    // Base case for 2x2 matrix
    if ($n == 2) {
        return $matrix[0][0] * $matrix[1][1] - $matrix[0][1] * $matrix[1][0];
    }

    $det = 0;
    for ($i = 0; $i < $n; $i++) {
        $subMatrix = getSubMatrix($matrix, 0, $i);
        $det += ($i % 2 == 0 ? 1 : -1) 
       * $matrix[0][$i] * determinant($subMatrix);
    }

    return $det;
}

// Function to get the submatrix by 
// removing the specified row and column
function getSubMatrix($matrix, $row, $col) {
    $subMatrix = array();
    for ($i = 1; $i < count($matrix); $i++) {
        $subRow = array();
        for ($j = 0; $j < count($matrix[$i]); $j++) {
            if ($j == $col) continue;
            $subRow[] = $matrix[$i][$j];
        }
        $subMatrix[] = $subRow;
    }
    return $subMatrix;
}

// Example matrix
$matrix = array(
    array(1, 2, 3),
    array(4, 5, 6),
    array(7, 8, 9)
);

echo "Determinant: " . determinant($matrix);
?>

Output
Determinant: 0

Time complexity: O(n!)

Auxiliary Space: O(n2)

Using Iterative approach

This method implements the PHP loops to iterate over the matrix elements and creates sub matrices to find the determinant of the matrix.

  • Initialize the determinant value (det) to 1 and a total scaling factor (total) to 1.
  • Create a temporary array to store intermediate values during row operations.
  • Iterate over each column to find the pivot element (non-zero element) in the current column. If no pivot is found, skip to the next column.
  • Swap rows to bring the pivot element to the diagonal position.
  • Apply row operations to create zeros below the pivot element.
  • Update the scaling factor total with the pivot element's value.
  • Multiply the diagonal elements of the transformed matrix.
  • Divide by the total scaling factor to get the determinant.

Example: The below code example is a practical implementation of the iterative approach to find determinant of the matrix.

PHP
<?php
// N is the order of the matrix
const N = 2;
 
function determinantOfMatrixIterative($mat, $n) {
    $det = 1;
    $total = 1;
    $temp = array_fill(0, $n, 0);
    for ($i = 0; $i < $n; $i++) {
        $index = $i;
        while ($index < $n && $mat[$index][$i] === 0) {
            $index++;
        }
        if ($index === $n) {
            continue;
        }
        if ($index !== $i) {
            for ($j = 0; $j < $n; $j++) {
                list($mat[$i][$j], $mat[$index][$j]) = 
                array($mat[$index][$j], $mat[$i][$j]);
            }
            $det *= pow(-1, $index - $i);
        }
        for ($j = 0; $j < $n; $j++) {
            $temp[$j] = $mat[$i][$j];
        }
        for ($j = $i + 1; $j < $n; $j++) {
            $num1 = $temp[$i];
            $num2 = $mat[$j][$i];
            for ($k = 0; $k < $n; $k++) {
                $mat[$j][$k] = 
                    $num1 * $mat[$j][$k] - 
                    $num2 * $temp[$k];
            }
            $total *= $num1;
        }
    }
    for ($i = 0; $i < $n; $i++) {
        $det *= $mat[$i][$i];
    }
    return $det / $total;
}
 
$mat = array(
    array(8, 1),
    array(2, 1),
  
);
echo "Determinant of the matrix is: " 
  . determinantOfMatrixIterative($mat, N);
?>

Output
Determinant of the matrix is: 6

Time Complexity: O(n2)

Auxiliary Space: O(n)


Next Article
Article Tags :

Similar Reads