first commit

This commit is contained in:
aschwarz
2022-11-28 10:27:30 +01:00
commit 9015dd2102
2720 changed files with 605111 additions and 0 deletions

View File

@ -0,0 +1,53 @@
<?php
namespace Matrix;
/**
*
* Autoloader for Matrix classes
*
* @package Matrix
* @copyright Copyright (c) 2014 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
class Autoloader
{
/**
* Register the Autoloader with SPL
*
*/
public static function Register()
{
if (function_exists('__autoload')) {
// Register any existing autoloader function with SPL, so we don't get any clashes
spl_autoload_register('__autoload');
}
// Register ourselves with SPL
return spl_autoload_register(['Matrix\\Autoloader', 'Load']);
}
/**
* Autoload a class identified by name
*
* @param string $pClassName Name of the object to load
*/
public static function Load($pClassName)
{
if ((class_exists($pClassName, false)) || (strpos($pClassName, 'Matrix\\') !== 0)) {
// Either already loaded, or not a Matrix class request
return false;
}
$pClassFilePath = __DIR__ . DIRECTORY_SEPARATOR .
'src' . DIRECTORY_SEPARATOR .
str_replace(['Matrix\\', '\\'], ['', '/'], $pClassName) .
'.php';
if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) {
// Can't load
return false;
}
require($pClassFilePath);
}
}

View File

@ -0,0 +1,38 @@
<?php
include_once __DIR__ . '/Autoloader.php';
\Matrix\Autoloader::Register();
abstract class FilesystemRegexFilter extends RecursiveRegexIterator
{
protected $regex;
public function __construct(RecursiveIterator $it, $regex)
{
$this->regex = $regex;
parent::__construct($it, $regex);
}
}
class FilenameFilter extends FilesystemRegexFilter
{
// Filter files against the regex
public function accept()
{
return (!$this->isFile() || preg_match($this->regex, $this->getFilename()));
}
}
$srcFolder = __DIR__ . DIRECTORY_SEPARATOR . 'src';
$srcDirectory = new RecursiveDirectoryIterator($srcFolder);
$filteredFileList = new FilenameFilter($srcDirectory, '/(?:php)$/i');
$filteredFileList = new FilenameFilter($filteredFileList, '/^(?!.*(Matrix|Exception)\.php).*$/i');
foreach (new RecursiveIteratorIterator($filteredFileList) as $file) {
if ($file->isFile()) {
include_once $file;
}
}

View File

@ -0,0 +1,70 @@
<?php
/**
*
* Class for the creating "special" Matrices
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Matrix Builder class.
*
* @package Matrix
*/
class Builder
{
/**
* Create a new matrix of specified dimensions, and filled with a specified value
* If the column argument isn't provided, then a square matrix will be created
*
* @param mixed $value
* @param int $rows
* @param int|null $columns
* @return Matrix
* @throws Exception
*/
public static function createFilledMatrix($value, $rows, $columns = null)
{
if ($columns === null) {
$columns = $rows;
}
$rows = Matrix::validateRow($rows);
$columns = Matrix::validateColumn($columns);
return new Matrix(
array_fill(
0,
$rows,
array_fill(
0,
$columns,
$value
)
)
);
}
/**
* Create a new identity matrix of specified dimensions
* This will always be a square matrix, with the number of rows and columns matching the provided dimension
*
* @param int $dimensions
* @return Matrix
* @throws Exception
*/
public static function createIdentityMatrix($dimensions)
{
$grid = static::createFilledMatrix(null, $dimensions)->toArray();
for ($x = 0; $x < $dimensions; ++$x) {
$grid[$x][$x] = 1;
}
return new Matrix($grid);
}
}

View File

@ -0,0 +1,13 @@
<?php
/**
* Exception.
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
class Exception extends \Exception
{
}

View File

@ -0,0 +1,337 @@
<?php
namespace Matrix;
class Functions
{
/**
* Calculate the adjoint of the matrix
*
* @param Matrix $matrix The matrix whose adjoint we wish to calculate
* @return Matrix
*
* @throws Exception
*/
private static function getAdjoint(Matrix $matrix)
{
return self::transpose(
self::getCofactors($matrix)
);
}
/**
* Return the adjoint of this matrix
* The adjugate, classical adjoint, or adjunct of a square matrix is the transpose of its cofactor matrix.
* The adjugate has sometimes been called the "adjoint", but today the "adjoint" of a matrix normally refers
* to its corresponding adjoint operator, which is its conjugate transpose.
*
* @param Matrix $matrix The matrix whose adjoint we wish to calculate
* @return Matrix
* @throws Exception
**/
public static function adjoint(Matrix $matrix)
{
if (!$matrix->isSquare()) {
throw new Exception('Adjoint can only be calculated for a square matrix');
}
return self::getAdjoint($matrix);
}
/**
* Calculate the cofactors of the matrix
*
* @param Matrix $matrix The matrix whose cofactors we wish to calculate
* @return Matrix
*
* @throws Exception
*/
private static function getCofactors(Matrix $matrix)
{
$cofactors = self::getMinors($matrix);
$dimensions = $matrix->rows;
$cof = 1;
for ($i = 0; $i < $dimensions; ++$i) {
$cofs = $cof;
for ($j = 0; $j < $dimensions; ++$j) {
$cofactors[$i][$j] *= $cofs;
$cofs = -$cofs;
}
$cof = -$cof;
}
return new Matrix($cofactors);
}
/**
* Return the cofactors of this matrix
*
* @param Matrix $matrix The matrix whose cofactors we wish to calculate
* @return Matrix
*
* @throws Exception
*/
public static function cofactors(Matrix $matrix)
{
if (!$matrix->isSquare()) {
throw new Exception('Cofactors can only be calculated for a square matrix');
}
return self::getCofactors($matrix);
}
/**
* @param Matrix $matrix
* @param int $row
* @param int $column
* @return float
* @throws Exception
*/
private static function getDeterminantSegment(Matrix $matrix, $row, $column)
{
$tmpMatrix = $matrix->toArray();
unset($tmpMatrix[$row]);
array_walk(
$tmpMatrix,
function (&$row) use ($column) {
unset($row[$column]);
}
);
return self::getDeterminant(new Matrix($tmpMatrix));
}
/**
* Calculate the determinant of the matrix
*
* @param Matrix $matrix The matrix whose determinant we wish to calculate
* @return float
*
* @throws Exception
*/
private static function getDeterminant(Matrix $matrix)
{
$dimensions = $matrix->rows;
$determinant = 0;
switch ($dimensions) {
case 1:
$determinant = $matrix->getValue(1, 1);
break;
case 2:
$determinant = $matrix->getValue(1, 1) * $matrix->getValue(2, 2) -
$matrix->getValue(1, 2) * $matrix->getValue(2, 1);
break;
default:
for ($i = 1; $i <= $dimensions; ++$i) {
$det = $matrix->getValue(1, $i) * self::getDeterminantSegment($matrix, 0, $i - 1);
if (($i % 2) == 0) {
$determinant -= $det;
} else {
$determinant += $det;
}
}
break;
}
return $determinant;
}
/**
* Return the determinant of this matrix
*
* @param Matrix $matrix The matrix whose determinant we wish to calculate
* @return float
* @throws Exception
**/
public static function determinant(Matrix $matrix)
{
if (!$matrix->isSquare()) {
throw new Exception('Determinant can only be calculated for a square matrix');
}
return self::getDeterminant($matrix);
}
/**
* Return the diagonal of this matrix
*
* @param Matrix $matrix The matrix whose diagonal we wish to calculate
* @return Matrix
* @throws Exception
**/
public static function diagonal(Matrix $matrix)
{
if (!$matrix->isSquare()) {
throw new Exception('Diagonal can only be extracted from a square matrix');
}
$dimensions = $matrix->rows;
$grid = Builder::createFilledMatrix(0, $dimensions, $dimensions)
->toArray();
for ($i = 0; $i < $dimensions; ++$i) {
$grid[$i][$i] = $matrix->getValue($i + 1, $i + 1);
}
return new Matrix($grid);
}
/**
* Return the antidiagonal of this matrix
*
* @param Matrix $matrix The matrix whose antidiagonal we wish to calculate
* @return Matrix
* @throws Exception
**/
public static function antidiagonal(Matrix $matrix)
{
if (!$matrix->isSquare()) {
throw new Exception('Anti-Diagonal can only be extracted from a square matrix');
}
$dimensions = $matrix->rows;
$grid = Builder::createFilledMatrix(0, $dimensions, $dimensions)
->toArray();
for ($i = 0; $i < $dimensions; ++$i) {
$grid[$i][$dimensions - $i - 1] = $matrix->getValue($i + 1, $dimensions - $i);
}
return new Matrix($grid);
}
/**
* Return the identity matrix
* The identity matrix, or sometimes ambiguously called a unit matrix, of size n is the n × n square matrix
* with ones on the main diagonal and zeros elsewhere
*
* @param Matrix $matrix The matrix whose identity we wish to calculate
* @return Matrix
* @throws Exception
**/
public static function identity(Matrix $matrix)
{
if (!$matrix->isSquare()) {
throw new Exception('Identity can only be created for a square matrix');
}
$dimensions = $matrix->rows;
return Builder::createIdentityMatrix($dimensions);
}
/**
* Return the inverse of this matrix
*
* @param Matrix $matrix The matrix whose inverse we wish to calculate
* @return Matrix
* @throws Exception
**/
public static function inverse(Matrix $matrix)
{
if (!$matrix->isSquare()) {
throw new Exception('Inverse can only be calculated for a square matrix');
}
$determinant = self::getDeterminant($matrix);
if ($determinant == 0.0) {
throw new Exception('Inverse can only be calculated for a matrix with a non-zero determinant');
}
if ($matrix->rows == 1) {
return new Matrix([[1 / $matrix->getValue(1, 1)]]);
}
return self::getAdjoint($matrix)
->multiply(1 / $determinant);
}
/**
* Calculate the minors of the matrix
*
* @param Matrix $matrix The matrix whose minors we wish to calculate
* @return array[]
*
* @throws Exception
*/
protected static function getMinors(Matrix $matrix)
{
$minors = $matrix->toArray();
$dimensions = $matrix->rows;
if ($dimensions == 1) {
return $minors;
}
for ($i = 0; $i < $dimensions; ++$i) {
for ($j = 0; $j < $dimensions; ++$j) {
$minors[$i][$j] = self::getDeterminantSegment($matrix, $i, $j);
}
}
return $minors;
}
/**
* Return the minors of the matrix
* The minor of a matrix A is the determinant of some smaller square matrix, cut down from A by removing one or
* more of its rows or columns.
* Minors obtained by removing just one row and one column from square matrices (first minors) are required for
* calculating matrix cofactors, which in turn are useful for computing both the determinant and inverse of
* square matrices.
*
* @param Matrix $matrix The matrix whose minors we wish to calculate
* @return Matrix
* @throws Exception
**/
public static function minors(Matrix $matrix)
{
if (!$matrix->isSquare()) {
throw new Exception('Minors can only be calculated for a square matrix');
}
return new Matrix(self::getMinors($matrix));
}
/**
* Return the trace of this matrix
* The trace is defined as the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right)
* of the matrix
*
* @param Matrix $matrix The matrix whose trace we wish to calculate
* @return float
* @throws Exception
**/
public static function trace(Matrix $matrix)
{
if (!$matrix->isSquare()) {
throw new Exception('Trace can only be extracted from a square matrix');
}
$dimensions = $matrix->rows;
$result = 0;
for ($i = 1; $i <= $dimensions; ++$i) {
$result += $matrix->getValue($i, $i);
}
return $result;
}
/**
* Return the transpose of this matrix
*
* @param Matrix $matrix The matrix whose transpose we wish to calculate
* @return Matrix
**/
public static function transpose(Matrix $matrix)
{
$array = array_values(array_merge([null], $matrix->toArray()));
$grid = call_user_func_array(
'array_map',
$array
);
return new Matrix($grid);
}
}

View File

@ -0,0 +1,400 @@
<?php
/**
*
* Class for the management of Matrices
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Matrix object.
*
* @package Matrix
*
* @property-read int $rows The number of rows in the matrix
* @property-read int $columns The number of columns in the matrix
* @method Matrix antidiagonal()
* @method Matrix adjoint()
* @method Matrix cofactors()
* @method float determinant()
* @method Matrix diagonal()
* @method Matrix identity()
* @method Matrix inverse()
* @method Matrix pseudoInverse()
* @method Matrix minors()
* @method float trace()
* @method Matrix transpose()
* @method Matrix add(...$matrices)
* @method Matrix subtract(...$matrices)
* @method Matrix multiply(...$matrices)
* @method Matrix divideby(...$matrices)
* @method Matrix divideinto(...$matrices)
*/
class Matrix
{
protected $rows;
protected $columns;
protected $grid = [];
/*
* Create a new Matrix object from an array of values
*
* @param array $grid
*/
final public function __construct(array $grid)
{
$this->buildFromArray(array_values($grid));
}
/*
* Create a new Matrix object from an array of values
*
* @param array $grid
*/
protected function buildFromArray(array $grid)
{
$this->rows = count($grid);
$columns = array_reduce(
$grid,
function ($carry, $value) {
return max($carry, is_array($value) ? count($value) : 1);
}
);
$this->columns = $columns;
array_walk(
$grid,
function (&$value) use ($columns) {
if (!is_array($value)) {
$value = [$value];
}
$value = array_pad(array_values($value), $columns, null);
}
);
$this->grid = $grid;
}
/**
* Validate that a row number is a positive integer
*
* @param int $row
* @return int
* @throws Exception
*/
public static function validateRow($row)
{
if ((!is_numeric($row)) || (intval($row) < 1)) {
throw new Exception('Invalid Row');
}
return (int)$row;
}
/**
* Validate that a column number is a positive integer
*
* @param int $column
* @return int
* @throws Exception
*/
public static function validateColumn($column)
{
if ((!is_numeric($column)) || (intval($column) < 1)) {
throw new Exception('Invalid Column');
}
return (int)$column;
}
/**
* Validate that a row number falls within the set of rows for this matrix
*
* @param int $row
* @return int
* @throws Exception
*/
protected function validateRowInRange($row)
{
$row = static::validateRow($row);
if ($row > $this->rows) {
throw new Exception('Requested Row exceeds matrix size');
}
return $row;
}
/**
* Validate that a column number falls within the set of columns for this matrix
*
* @param int $column
* @return int
* @throws Exception
*/
protected function validateColumnInRange($column)
{
$column = static::validateColumn($column);
if ($column > $this->columns) {
throw new Exception('Requested Column exceeds matrix size');
}
return $column;
}
/**
* Return a new matrix as a subset of rows from this matrix, starting at row number $row, and $rowCount rows
* A $rowCount value of 0 will return all rows of the matrix from $row
* A negative $rowCount value will return rows until that many rows from the end of the matrix
*
* Note that row numbers start from 1, not from 0
*
* @param int $row
* @param int $rowCount
* @return static
* @throws Exception
*/
public function getRows($row, $rowCount = 1)
{
$row = $this->validateRowInRange($row);
if ($rowCount === 0) {
$rowCount = $this->rows - $row + 1;
}
return new static(array_slice($this->grid, $row - 1, (int)$rowCount));
}
/**
* Return a new matrix as a subset of columns from this matrix, starting at column number $column, and $columnCount columns
* A $columnCount value of 0 will return all columns of the matrix from $column
* A negative $columnCount value will return columns until that many columns from the end of the matrix
*
* Note that column numbers start from 1, not from 0
*
* @param int $column
* @param int $columnCount
* @return Matrix
* @throws Exception
*/
public function getColumns($column, $columnCount = 1)
{
$column = $this->validateColumnInRange($column);
if ($columnCount < 1) {
$columnCount = $this->columns + $columnCount - $column + 1;
}
$grid = [];
for ($i = $column - 1; $i < $column + $columnCount - 1; ++$i) {
$grid[] = array_column($this->grid, $i);
}
return (new static($grid))->transpose();
}
/**
* Return a new matrix as a subset of rows from this matrix, dropping rows starting at row number $row,
* and $rowCount rows
* A negative $rowCount value will drop rows until that many rows from the end of the matrix
* A $rowCount value of 0 will remove all rows of the matrix from $row
*
* Note that row numbers start from 1, not from 0
*
* @param int $row
* @param int $rowCount
* @return static
* @throws Exception
*/
public function dropRows($row, $rowCount = 1)
{
$this->validateRowInRange($row);
if ($rowCount === 0) {
$rowCount = $this->rows - $row + 1;
}
$grid = $this->grid;
array_splice($grid, $row - 1, (int)$rowCount);
return new static($grid);
}
/**
* Return a new matrix as a subset of columns from this matrix, dropping columns starting at column number $column,
* and $columnCount columns
* A negative $columnCount value will drop columns until that many columns from the end of the matrix
* A $columnCount value of 0 will remove all columns of the matrix from $column
*
* Note that column numbers start from 1, not from 0
*
* @param int $column
* @param int $columnCount
* @return static
* @throws Exception
*/
public function dropColumns($column, $columnCount = 1)
{
$this->validateColumnInRange($column);
if ($columnCount < 1) {
$columnCount = $this->columns + $columnCount - $column + 1;
}
$grid = $this->grid;
array_walk(
$grid,
function (&$row) use ($column, $columnCount) {
array_splice($row, $column - 1, (int)$columnCount);
}
);
return new static($grid);
}
/**
* Return a value from this matrix, from the "cell" identified by the row and column numbers
* Note that row and column numbers start from 1, not from 0
*
* @param int $row
* @param int $column
* @return mixed
* @throws Exception
*/
public function getValue($row, $column)
{
$row = $this->validateRowInRange($row);
$column = $this->validateColumnInRange($column);
return $this->grid[$row - 1][$column - 1];
}
/**
* Returns a Generator that will yield each row of the matrix in turn as a vector matrix
* or the value of each cell if the matrix is a vector
*
* @return \Generator|Matrix[]|mixed[]
*/
public function rows()
{
foreach ($this->grid as $i => $row) {
yield $i + 1 => ($this->columns == 1)
? $row[0]
: new static([$row]);
}
}
/**
* Returns a Generator that will yield each column of the matrix in turn as a vector matrix
* or the value of each cell if the matrix is a vector
*
* @return \Generator|Matrix[]|mixed[]
*/
public function columns()
{
for ($i = 0; $i < $this->columns; ++$i) {
yield $i + 1 => ($this->rows == 1)
? $this->grid[0][$i]
: new static(array_column($this->grid, $i));
}
}
/**
* Identify if the row and column dimensions of this matrix are equal,
* i.e. if it is a "square" matrix
*
* @return bool
*/
public function isSquare()
{
return $this->rows == $this->columns;
}
/**
* Identify if this matrix is a vector
* i.e. if it comprises only a single row or a single column
*
* @return bool
*/
public function isVector()
{
return $this->rows == 1 || $this->columns == 1;
}
/**
* Return the matrix as a 2-dimensional array
*
* @return array
*/
public function toArray()
{
return $this->grid;
}
protected static $getters = [
'rows',
'columns',
];
/**
* Access specific properties as read-only (no setters)
*
* @param string $propertyName
* @return mixed
* @throws Exception
*/
public function __get($propertyName)
{
$propertyName = strtolower($propertyName);
// Test for function calls
if (in_array($propertyName, self::$getters)) {
return $this->$propertyName;
}
throw new Exception('Property does not exist');
}
protected static $functions = [
'antidiagonal',
'adjoint',
'cofactors',
'determinant',
'diagonal',
'identity',
'inverse',
'minors',
'trace',
'transpose',
];
protected static $operations = [
'add',
'subtract',
'multiply',
'divideby',
'divideinto',
'directsum',
];
/**
* Returns the result of the function call or operation
*
* @param string $functionName
* @param mixed[] $arguments
* @return Matrix|float
* @throws Exception
*/
public function __call($functionName, $arguments)
{
$functionName = strtolower(str_replace('_', '', $functionName));
if (in_array($functionName, self::$functions) || in_array($functionName, self::$operations)) {
$functionName = "\\" . __NAMESPACE__ . "\\{$functionName}";
if (is_callable($functionName)) {
$arguments = array_values(array_merge([$this], $arguments));
return call_user_func_array($functionName, $arguments);
}
}
throw new Exception('Function or Operation does not exist');
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace Matrix\Operators;
use Matrix\Matrix;
use Matrix\Exception;
class Addition extends Operator
{
/**
* Execute the addition
*
* @param mixed $value The matrix or numeric value to add to the current base value
* @throws Exception If the provided argument is not appropriate for the operation
* @return $this The operation object, allowing multiple additions to be chained
**/
public function execute($value)
{
if (is_array($value)) {
$value = new Matrix($value);
}
if (is_object($value) && ($value instanceof Matrix)) {
return $this->addMatrix($value);
} elseif (is_numeric($value)) {
return $this->addScalar($value);
}
throw new Exception('Invalid argument for addition');
}
/**
* Execute the addition for a scalar
*
* @param mixed $value The numeric value to add to the current base value
* @return $this The operation object, allowing multiple additions to be chained
**/
protected function addScalar($value)
{
for ($row = 0; $row < $this->rows; ++$row) {
for ($column = 0; $column < $this->columns; ++$column) {
$this->matrix[$row][$column] += $value;
}
}
return $this;
}
/**
* Execute the addition for a matrix
*
* @param Matrix $value The numeric value to add to the current base value
* @return $this The operation object, allowing multiple additions to be chained
* @throws Exception If the provided argument is not appropriate for the operation
**/
protected function addMatrix(Matrix $value)
{
$this->validateMatchingDimensions($value);
for ($row = 0; $row < $this->rows; ++$row) {
for ($column = 0; $column < $this->columns; ++$column) {
$this->matrix[$row][$column] += $value->getValue($row + 1, $column + 1);
}
}
return $this;
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace Matrix\Operators;
use Matrix\Matrix;
use Matrix\Exception;
class DirectSum extends Operator
{
/**
* Execute the addition
*
* @param mixed $value The matrix or numeric value to add to the current base value
* @return $this The operation object, allowing multiple additions to be chained
* @throws Exception If the provided argument is not appropriate for the operation
*/
public function execute($value)
{
if (is_array($value)) {
$value = new Matrix($value);
}
if ($value instanceof Matrix) {
return $this->directSumMatrix($value);
}
throw new Exception('Invalid argument for addition');
}
/**
* Execute the direct sum for a matrix
*
* @param Matrix $value The numeric value to concatenate/direct sum with the current base value
* @return $this The operation object, allowing multiple additions to be chained
**/
private function directSumMatrix($value)
{
$originalColumnCount = count($this->matrix[0]);
$originalRowCount = count($this->matrix);
$valColumnCount = $value->columns;
$valRowCount = $value->rows;
$value = $value->toArray();
for ($row = 0; $row < $this->rows; ++$row) {
$this->matrix[$row] = array_merge($this->matrix[$row], array_fill(0, $valColumnCount, 0));
}
$this->matrix = array_merge(
$this->matrix,
array_fill(0, $valRowCount, array_fill(0, $originalColumnCount, 0))
);
for ($row = $originalRowCount; $row < $originalRowCount + $valRowCount; ++$row) {
array_splice(
$this->matrix[$row],
$originalColumnCount,
$valColumnCount,
$value[$row - $originalRowCount]
);
}
return $this;
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace Matrix\Operators;
use \Matrix\Matrix;
use \Matrix\Functions;
use Matrix\Exception;
class Division extends Multiplication
{
/**
* Execute the division
*
* @param mixed $value The matrix or numeric value to divide the current base value by
* @throws Exception If the provided argument is not appropriate for the operation
* @return $this The operation object, allowing multiple divisions to be chained
**/
public function execute($value)
{
if (is_array($value)) {
$value = new Matrix($value);
}
if (is_object($value) && ($value instanceof Matrix)) {
try {
$value = Functions::inverse($value);
} catch (Exception $e) {
throw new Exception('Division can only be calculated using a matrix with a non-zero determinant');
}
return $this->multiplyMatrix($value);
} elseif (is_numeric($value)) {
return $this->multiplyScalar(1 / $value);
}
throw new Exception('Invalid argument for division');
}
}

View File

@ -0,0 +1,77 @@
<?php
namespace Matrix\Operators;
use Matrix\Matrix;
use \Matrix\Builder;
use Matrix\Exception;
class Multiplication extends Operator
{
/**
* Execute the multiplication
*
* @param mixed $value The matrix or numeric value to multiply the current base value by
* @throws Exception If the provided argument is not appropriate for the operation
* @return $this The operation object, allowing multiple multiplications to be chained
**/
public function execute($value)
{
if (is_array($value)) {
$value = new Matrix($value);
}
if (is_object($value) && ($value instanceof Matrix)) {
return $this->multiplyMatrix($value);
} elseif (is_numeric($value)) {
return $this->multiplyScalar($value);
}
throw new Exception('Invalid argument for multiplication');
}
/**
* Execute the multiplication for a scalar
*
* @param mixed $value The numeric value to multiply with the current base value
* @return $this The operation object, allowing multiple mutiplications to be chained
**/
protected function multiplyScalar($value)
{
for ($row = 0; $row < $this->rows; ++$row) {
for ($column = 0; $column < $this->columns; ++$column) {
$this->matrix[$row][$column] *= $value;
}
}
return $this;
}
/**
* Execute the multiplication for a matrix
*
* @param Matrix $value The numeric value to multiply with the current base value
* @return $this The operation object, allowing multiple mutiplications to be chained
* @throws Exception If the provided argument is not appropriate for the operation
**/
protected function multiplyMatrix(Matrix $value)
{
$this->validateReflectingDimensions($value);
$newRows = $this->rows;
$newColumns = $value->columns;
$matrix = Builder::createFilledMatrix(0, $newRows, $newColumns)
->toArray();
for ($row = 0; $row < $newRows; ++$row) {
for ($column = 0; $column < $newColumns; ++$column) {
$columnData = $value->getColumns($column + 1)->toArray();
foreach ($this->matrix[$row] as $key => $valueData) {
$matrix[$row][$column] += $valueData * $columnData[$key][0];
}
}
}
$this->matrix = $matrix;
return $this;
}
}

View File

@ -0,0 +1,78 @@
<?php
namespace Matrix\Operators;
use Matrix\Matrix;
use Matrix\Exception;
abstract class Operator
{
/**
* Stored internally as a 2-dimension array of values
*
* @property mixed[][] $matrix
**/
protected $matrix;
/**
* Number of rows in the matrix
*
* @property integer $rows
**/
protected $rows;
/**
* Number of columns in the matrix
*
* @property integer $columns
**/
protected $columns;
/**
* Create an new handler object for the operation
*
* @param Matrix $matrix The base Matrix object on which the operation will be performed
*/
public function __construct(Matrix $matrix)
{
$this->rows = $matrix->rows;
$this->columns = $matrix->columns;
$this->matrix = $matrix->toArray();
}
/**
* Compare the dimensions of the matrices being operated on to see if they are valid for addition/subtraction
*
* @param Matrix $matrix The second Matrix object on which the operation will be performed
* @throws Exception
*/
protected function validateMatchingDimensions(Matrix $matrix)
{
if (($this->rows != $matrix->rows) || ($this->columns != $matrix->columns)) {
throw new Exception('Matrices have mismatched dimensions');
}
}
/**
* Compare the dimensions of the matrices being operated on to see if they are valid for multiplication/division
*
* @param Matrix $matrix The second Matrix object on which the operation will be performed
* @throws Exception
*/
protected function validateReflectingDimensions(Matrix $matrix)
{
if ($this->columns != $matrix->rows) {
throw new Exception('Matrices have mismatched dimensions');
}
}
/**
* Return the result of the operation
*
* @return Matrix
*/
public function result()
{
return new Matrix($this->matrix);
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace Matrix\Operators;
use Matrix\Matrix;
use Matrix\Exception;
class Subtraction extends Operator
{
/**
* Execute the subtraction
*
* @param mixed $value The matrix or numeric value to subtract from the current base value
* @throws Exception If the provided argument is not appropriate for the operation
* @return $this The operation object, allowing multiple subtractions to be chained
**/
public function execute($value)
{
if (is_array($value)) {
$value = new Matrix($value);
}
if (is_object($value) && ($value instanceof Matrix)) {
return $this->subtractMatrix($value);
} elseif (is_numeric($value)) {
return $this->subtractScalar($value);
}
throw new Exception('Invalid argument for subtraction');
}
/**
* Execute the subtraction for a scalar
*
* @param mixed $value The numeric value to subtracted from the current base value
* @return $this The operation object, allowing multiple additions to be chained
**/
protected function subtractScalar($value)
{
for ($row = 0; $row < $this->rows; ++$row) {
for ($column = 0; $column < $this->columns; ++$column) {
$this->matrix[$row][$column] -= $value;
}
}
return $this;
}
/**
* Execute the subtraction for a matrix
*
* @param Matrix $value The numeric value to subtract from the current base value
* @return $this The operation object, allowing multiple subtractions to be chained
* @throws Exception If the provided argument is not appropriate for the operation
**/
protected function subtractMatrix(Matrix $value)
{
$this->validateMatchingDimensions($value);
for ($row = 0; $row < $this->rows; ++$row) {
for ($column = 0; $column < $this->columns; ++$column) {
$this->matrix[$row][$column] -= $value->getValue($row + 1, $column + 1);
}
}
return $this;
}
}

View File

@ -0,0 +1,30 @@
<?php
/**
*
* Function code for the matrix adjoint() function
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Returns the adjoint of a matrix or an array.
*
* @param Matrix|array $matrix Matrix or an array to treat as a matrix.
* @return Matrix The new matrix
* @throws Exception If argument isn't a valid matrix or array.
*/
function adjoint($matrix)
{
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Must be Matrix or array');
}
return Functions::adjoint($matrix);
}

View File

@ -0,0 +1,29 @@
<?php
/**
*
* Function code for the matrix antidiagonal() function
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Returns the antidiagonal of a matrix or an array.
*
* @param Matrix|array $matrix Matrix or an array to treat as a matrix.
* @return Matrix The new matrix
* @throws Exception If argument isn't a valid matrix or array.
*/
function antidiagonal($matrix)
{
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Must be Matrix or array');
}
return Functions::antidiagonal($matrix);
}

View File

@ -0,0 +1,30 @@
<?php
/**
*
* Function code for the matrix cofactors() function
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Returns the cofactors of a matrix or an array.
*
* @param Matrix|array $matrix Matrix or an array to treat as a matrix.
* @return Matrix The new matrix
* @throws Exception If argument isn't a valid matrix or array.
*/
function cofactors($matrix)
{
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Must be Matrix or array');
}
return Functions::cofactors($matrix);
}

View File

@ -0,0 +1,30 @@
<?php
/**
*
* Function code for the matrix determinant() function
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Returns the determinant of a matrix or an array.
*
* @param Matrix|array $matrix Matrix or an array to treat as a matrix.
* @return float Matrix determinant
* @throws Exception If argument isn't a valid matrix or array.
*/
function determinant($matrix)
{
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Must be Matrix or array');
}
return Functions::determinant($matrix);
}

View File

@ -0,0 +1,30 @@
<?php
/**
*
* Function code for the matrix diagonal() function
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Returns the diagonal of a matrix or an array.
*
* @param Matrix|array $matrix Matrix or an array to treat as a matrix.
* @return Matrix The new matrix
* @throws Exception If argument isn't a valid matrix or array.
*/
function diagonal($matrix)
{
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Must be Matrix or array');
}
return Functions::diagonal($matrix);
}

View File

@ -0,0 +1,30 @@
<?php
/**
*
* Function code for the matrix identity() function
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Returns the identity of a matrix or an array.
*
* @param Matrix|array $matrix Matrix or an array to treat as a matrix.
* @return Matrix The identity matrix
* @throws Exception If argument isn't a valid matrix or array.
*/
function identity($matrix)
{
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Must be Matrix or array');
}
return Functions::identity($matrix);
}

View File

@ -0,0 +1,30 @@
<?php
/**
*
* Function code for the matrix inverse() function
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Returns the inverse of a matrix or an array.
*
* @param Matrix|array $matrix Matrix or an array to treat as a matrix.
* @return Matrix The new matrix
* @throws Exception If argument isn't a valid matrix or array.
*/
function inverse($matrix)
{
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Must be Matrix or array');
}
return Functions::inverse($matrix);
}

View File

@ -0,0 +1,30 @@
<?php
/**
*
* Function code for the matrix minors() function
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Returns the minors of a matrix or an array.
*
* @param Matrix|array $matrix Matrix or an array to treat as a matrix.
* @return Matrix The new matrix
* @throws Exception If argument isn't a valid matrix or array.
*/
function minors($matrix)
{
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Must be Matrix or array');
}
return Functions::minors($matrix);
}

View File

@ -0,0 +1,30 @@
<?php
/**
*
* Function code for the matrix trace() function
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Returns the trace of a matrix or an array.
*
* @param Matrix|array $matrix Matrix or an array to treat as a matrix.
* @return float The trace of the matrix
* @throws Exception If argument isn't a valid matrix or array.
*/
function trace($matrix)
{
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Must be Matrix or array');
}
return Functions::trace($matrix);
}

View File

@ -0,0 +1,30 @@
<?php
/**
*
* Function code for the matrix transpose() function
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
/**
* Returns the transpose of a matrix or an array.
*
* @param Matrix|array $matrix Matrix or an array to treat as a matrix.
* @return Matrix The transposed matrix
* @throws Exception If argument isn't a valid matrix or array.
*/
function transpose($matrix)
{
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Must be Matrix or array');
}
return Functions::transpose($matrix);
}

View File

@ -0,0 +1,44 @@
<?php
/**
*
* Function code for the matrix addition operation
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
use Matrix\Operators\Addition;
/**
* Adds two or more matrices
*
* @param array<int, mixed> $matrixValues The matrices to add
* @return Matrix
* @throws Exception
*/
function add(...$matrixValues)
{
if (count($matrixValues) < 2) {
throw new Exception('Addition operation requires at least 2 arguments');
}
$matrix = array_shift($matrixValues);
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Addition arguments must be Matrix or array');
}
$result = new Addition($matrix);
foreach ($matrixValues as $matrix) {
$result->execute($matrix);
}
return $result->result();
}

View File

@ -0,0 +1,44 @@
<?php
/**
*
* Function code for the matrix direct sum operation
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
use Matrix\Operators\DirectSum;
/**
* Adds two or more matrices
*
* @param array<int, mixed> $matrixValues The matrices to add
* @return Matrix
* @throws Exception
*/
function directsum(...$matrixValues)
{
if (count($matrixValues) < 2) {
throw new Exception('DirectSum operation requires at least 2 arguments');
}
$matrix = array_shift($matrixValues);
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('DirectSum arguments must be Matrix or array');
}
$result = new DirectSum($matrix);
foreach ($matrixValues as $matrix) {
$result->execute($matrix);
}
return $result->result();
}

View File

@ -0,0 +1,44 @@
<?php
/**
*
* Function code for the matrix division operation
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
use Matrix\Operators\Division;
/**
* Divides two or more matrix numbers
*
* @param array<int, mixed> $matrixValues The matrices to divide
* @return Matrix
* @throws Exception
*/
function divideby(...$matrixValues)
{
if (count($matrixValues) < 2) {
throw new Exception('Division operation requires at least 2 arguments');
}
$matrix = array_shift($matrixValues);
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Division arguments must be Matrix or array');
}
$result = new Division($matrix);
foreach ($matrixValues as $matrix) {
$result->execute($matrix);
}
return $result->result();
}

View File

@ -0,0 +1,44 @@
<?php
/**
*
* Function code for the matrix division operation
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
use Matrix\Operators\Division;
/**
* Divides two or more matrix numbers
*
* @param array<int, mixed> $matrixValues The numbers to divide
* @return Matrix
* @throws Exception
*/
function divideinto(...$matrixValues)
{
if (count($matrixValues) < 2) {
throw new Exception('Division operation requires at least 2 arguments');
}
$matrix = array_shift($matrixValues);
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Division arguments must be Matrix or array');
}
$result = new Division($matrix);
foreach ($matrixValues as $matrix) {
$result->execute($matrix);
}
return $result->result();
}

View File

@ -0,0 +1,44 @@
<?php
/**
*
* Function code for the matrix multiplication operation
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
use Matrix\Operators\Multiplication;
/**
* Multiplies two or more matrices
*
* @param array<int, mixed> $matrixValues The matrices to multiply
* @return Matrix
* @throws Exception
*/
function multiply(...$matrixValues)
{
if (count($matrixValues) < 2) {
throw new Exception('Multiplication operation requires at least 2 arguments');
}
$matrix = array_shift($matrixValues);
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Multiplication arguments must be Matrix or array');
}
$result = new Multiplication($matrix);
foreach ($matrixValues as $matrix) {
$result->execute($matrix);
}
return $result->result();
}

View File

@ -0,0 +1,44 @@
<?php
/**
*
* Function code for the matrix subtraction operation
*
* @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Matrix;
use Matrix\Operators\Subtraction;
/**
* Subtracts two or more matrices
*
* @param array<int, mixed> $matrixValues The matrices to subtract
* @return Matrix
* @throws Exception
*/
function subtract(...$matrixValues)
{
if (count($matrixValues) < 2) {
throw new Exception('Subtraction operation requires at least 2 arguments');
}
$matrix = array_shift($matrixValues);
if (is_array($matrix)) {
$matrix = new Matrix($matrix);
}
if (!$matrix instanceof Matrix) {
throw new Exception('Subtraction arguments must be Matrix or array');
}
$result = new Subtraction($matrix);
foreach ($matrixValues as $matrix) {
$result->execute($matrix);
}
return $result->result();
}