Skip to content

Instantly share code, notes, and snippets.

@andrewmy
Created January 23, 2024 10:24
Show Gist options
  • Save andrewmy/2045df5b7401f894b490348fcfb8bba1 to your computer and use it in GitHub Desktop.
Save andrewmy/2045df5b7401f894b490348fcfb8bba1 to your computer and use it in GitHub Desktop.
Solving a random set of equations as a matrix
#!/usr/bin/env php
<?php
use MathPHP\LinearAlgebra\MatrixFactory;
use MathPHP\LinearAlgebra\Vector;
/**
* composer require markrogoyski/math-php
*/
require_once __DIR__ . '/vendor/autoload.php';
/** Create a matrix for the following set of equations:
*
* -A1X+B1Y-C1Z+D1T+E1U+F1V=2465
* A2X+B2Y+C2Z-D2T-E2U+F2V=2135
* A3X+B3Y-C3Z-D3T+E3U+F3V=5272
* -A4X-B4Y+C4Z+D4T+E4U-F4V=1455
* -A5X+B5Y+C5Z+D5T-E5U+F5V=-5514
* A6X-B6Y-C6Z-D6T+E6U+F6V=-1498
*
* Solving for X, Y, Z, T, U un V
*
* Placeholder values:
* A1 1937. A2 1927. A3 1936. A4 1970. A5 1906. A6 1924.
* B1 1920. B2 1933. B3 1926. B4 1941. B5 1921. B6 1917.
* C1 1894. C2 57. C3 2008. C4 1834. C5 1939. C6 1922.
* D1 1997. D2 1919. D3 2006. D4 1945. D5 1970. D6 1940.
* E1 1964. E2 1938. E3 8. E4 1941. E5 1941. E6 72.
* F1 1961. F2 05. F3 7. F4 1935. F5 1936. F6 12.
*/
$A = MatrixFactory::create([
[-1937, 1920, -1894, 1997, 1964, 1961],
[1927, 1933, 57, -1919, -1938, 5],
[1936, 1926, -2008, -2006, 8, 7],
[-1970, -1941, 1834, 1945, 1941, -1935],
[-1906, 1921, 1939, 1970, -1941, 1936],
[1924, -1917, -1922, -1940, 72, 12],
]);
$b = new Vector([2465, 2135, 5272, 1455, -5514, -1498]);
$solution = $A->solve($b)->getVector();
echo "X = {$solution[0]}
Y = {$solution[1]}
Z = {$solution[2]}
T = {$solution[3]}
U = {$solution[4]}
V = {$solution[5]}
";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment