Skip to content

Instantly share code, notes, and snippets.

@sagittaracc
Created November 18, 2022 07:50
Show Gist options
  • Save sagittaracc/bcd5e9524508c54ec8dc31516fc168cf to your computer and use it in GitHub Desktop.
Save sagittaracc/bcd5e9524508c54ec8dc31516fc168cf to your computer and use it in GitHub Desktop.
php matrix determinant
<?php
$matrix = [
1, 1, 1, 1,
4, 3, 2, 1,
2, 3, 4, 1,
3, 4, 3, 1
];
require 'Matrix.php';
$matrix = (new Matrix(4, 4))->load($matrix);
echo $matrix->det();
<?php
class Matrix
{
private $rows = 0;
private $cols = 0;
private $data = null;
public function __construct($rows, $cols)
{
$this->rows = $rows;
$this->cols = $cols;
}
public function load($data)
{
if (count($data) === $this->rows * $this->cols) {
$this->data = $data;
}
else {
$this->rows = 0;
$this->cols = 0;
}
return $this;
}
public function getLinearIndex($i, $j)
{
return $this->cols * $i + $j;
}
public function get($i, $j)
{
$index = $this->getLinearIndex($i, $j);
return isset($this->data[$index]) ? $this->data[$index] : null;
}
public function getAlgebraicExtension($ci, $cj)
{
$matrix = [];
for ($i = 0; $i < $this->rows; $i++) {
if ($i === $ci) continue;
for ($j = 0; $j < $this->cols; $j++) {
if ($j === $cj) continue;
$matrix[] = $this->get($i, $j);
}
}
return $matrix;
}
public function det()
{
$s = 0;
if ($this->rows === 2 && $this->cols === 2) {
return $this->get(0, 0) * $this->get(1, 1) - $this->get(1, 0) * $this->get(0, 1);
}
for ($j = 0; $j < $this->cols; $j++) {
$matrix = (new Matrix($this->rows - 1, $this->cols - 1))->load($this->getAlgebraicExtension(0, $j));
$s += $this->get(0, $j) * pow(-1, $j) * $matrix->det();
}
return $s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment