This repository has been archived by the owner on Jul 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 167
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
find_the_cofactor_of_a_matrix (#5717)
- Loading branch information
1 parent
cd6bf84
commit b876767
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
62 changes: 62 additions & 0 deletions
62
program/program/find-the-cofactor-of-a-matrix/find_the_cofactor_of_a_matrix.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
<?php | ||
|
||
function getCofactor($matrix, $p, $q) { | ||
$temp = []; | ||
$n = count($matrix); | ||
$i = 0; | ||
$j = 0; | ||
|
||
for ($row = 0; $row < $n; $row++) { | ||
for ($col = 0; $col < $n; $col++) { | ||
if ($row != $p && $col != $q) { | ||
$temp[$i][$j++] = $matrix[$row][$col]; | ||
if ($j == $n - 1) { | ||
$j = 0; | ||
$i++; | ||
} | ||
} | ||
} | ||
} | ||
return $temp; | ||
} | ||
|
||
function determinant($matrix, $n) { | ||
if ($n == 1) { | ||
return $matrix[0][0]; | ||
} | ||
$temp = []; | ||
$sign = 1; | ||
$d = 0; | ||
|
||
for ($f = 0; $f < $n; $f++) { | ||
$temp = getCofactor($matrix, 0, $f); | ||
$d += $sign * $matrix[0][$f] * determinant($temp, $n - 1); | ||
$sign = -$sign; | ||
} | ||
return $d; | ||
} | ||
|
||
function cofactor($matrix) { | ||
$n = count($matrix); | ||
$cofactorMatrix = []; | ||
|
||
for ($i = 0; $i < $n; $i++) { | ||
for ($j = 0; $j < $n; $j++) { | ||
$temp = getCofactor($matrix, $i, $j); | ||
$cofactorMatrix[$i][$j] = determinant($temp, $n - 1) * pow(-1, $i + $j); | ||
} | ||
} | ||
return $cofactorMatrix; | ||
} | ||
|
||
$matrix = [ | ||
[1, 2, 3], | ||
[4, 5, 6], | ||
[7, 8, 9] | ||
]; | ||
|
||
$cofactorMatrix = cofactor($matrix); | ||
foreach ($cofactorMatrix as $row) { | ||
echo "[" . implode(", ", $row) . "]\n"; | ||
} | ||
|