PHPackages                             chippyash/math-matrix - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. chippyash/math-matrix

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

chippyash/math-matrix
=====================

Matrix maths package

2.1.0(8y ago)21322BSD-3-ClausePHPPHP &gt;=5.6CI failing

Since Mar 4Pushed 8y ago1 watchersCompare

[ Source](https://github.com/chippyash/Math-Matrix)[ Packagist](https://packagist.org/packages/chippyash/math-matrix)[ Docs](http://zf4.biz/packages?utm_source=packagist&utm_medium=web&utm_campaign=blinks&utm_content=mathmatrix)[ RSS](/packages/chippyash-math-matrix/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (8)Versions (15)Used By (0)

chippyash/Math-Matrix
=====================

[](#chippyashmath-matrix)

Quality
-------

[](#quality)

[![PHP 5.6](https://camo.githubusercontent.com/88093c79af42bd3c07f4d6aa378289e1f5450411c56753b0323bd7d8b9b1f9ee/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d352e362d626c75652e737667)](https://camo.githubusercontent.com/88093c79af42bd3c07f4d6aa378289e1f5450411c56753b0323bd7d8b9b1f9ee/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d352e362d626c75652e737667)[![PHP 7](https://camo.githubusercontent.com/d23ce60b89c28c023d0ca69981ec9afbb17eb08a9cd1b609fd84c15d0732b7ce/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d372d626c75652e737667)](https://camo.githubusercontent.com/d23ce60b89c28c023d0ca69981ec9afbb17eb08a9cd1b609fd84c15d0732b7ce/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d372d626c75652e737667)[![Build Status](https://camo.githubusercontent.com/7d688795698cd8504e1dff87be648135f81b214cecae07a465710085a435d949/68747470733a2f2f7472617669732d63692e6f72672f6368697070796173682f4d6174682d4d61747269782e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/chippyash/Math-Matrix)[![Test Coverage](https://camo.githubusercontent.com/526dca30da076d2a1d12da2ce97c1d401a07092264f2238ae96179ea5ea01478/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f6368697070796173682f4d6174682d4d61747269782f6261646765732f636f7665726167652e737667)](https://codeclimate.com/github/chippyash/Math-Matrix/coverage)[![Code Climate](https://camo.githubusercontent.com/93f3a96f62dac2dfa20d05760de9947d3b737523f17478a42fa5daa62d058b5c/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f6368697070796173682f4d6174682d4d61747269782f6261646765732f6770612e737667)](https://codeclimate.com/github/chippyash/Math-Matrix)

The above badges represent the current development branch. As a rule, I don't push to GitHub unless tests, coverage and usability are acceptable. This may not be true for short periods of time; on holiday, need code for some other downstream project etc. If you need stable code, use a tagged version. Read 'Further Documentation' and 'Installation'.

See the [Test Contract](https://github.com/chippyash/Math-Matrix/blob/master/docs/Test-Contract.md) (526 tests, 820 assertions)

See the [API Documentation](http://chippyash.github.io/Math-Matrix/) for further information

Please note that developer support for PHP5.4 &amp; 5.5 was withdrawn at version 2.0.0 of this library. If you need support for PHP 5.4 or 5.5, please use a version `>=1,compute($fMul, $mB)
    //same as
    $mC = $fMul->compute($mA, $mB);
```

#### You can derive other information from a matrix

[](#you-can-derive-other-information-from-a-matrix)

- Derivatives always return a numeric result
- The original matrix is untouched
- You can use the magic \_\_invoke functionality
- Derivatives implement the Chippyash\\Math\\Matrix\\Interfaces\\DerivativeInterface

Four derivatives are currently supplied.

- Determinant

```
    $det = $mA("Determinant");
    //same as
    $fDet = new Chippyash\Math\Matrix\Derivative\Determinant();
    $det = $mA->derive($fDet);
    //same as
    $det = $fDet($mA);
```

As noted above, the Determinant derivative currently only supports up to a 20x20 matrix in auto mode. It will bork if you supply a matrix bigger than that. This will be ok for most purposes. If you are happy to wait a while to compute determinants for bigger matrices, create the determinant by construction (second way above) and specify Determinant::METHOD\_LU as a construction parameter. Determinant::METHOD\_LAPLACE is left for historical reasons, as there is very little likelihood you will want to use it!

- Trace. Returns the trace of a square matrix

```
    $tr = $mA('Trace');
    //or other variations as with Determinant
```

- Sum. Simply sums all the vertices in the matrix and returns the result

```
    $sum = $mA('Sum');
    //or other variations as with Determinant
```

- MarkovWeightedRandom. Return the next step using Random Weighted method on a Markov Chain Matrix

```
    $mA = new NumericMatrix(
        [
            [0,2,0,8]  //row 1
            [1,0,0,0]  //row 2
            [0,0,5,5]  //row 3
            [0,1,6,3]  //row 4
        ]
    )

    $next = $mA('MarkovWeightedRandom', TypeFactory::createInt(3));
    //will return IntType(3) or IntType(4) with 50% chance of either being returned

```

A NotMarkovException will be thrown if the supplied Matrix does not conform to the IsMarkov Attribute. Please note, that whilst you can supply a matrix with floats, the nature of mt\_rand() function used to generate the next number means that, for the time being, you should provide integer values. As long as you supply a square matrix where each row row sums to the same number, you have a Markov Chain expressed as a Matrix.

#### Additional transformations are supported by numeric matrices

[](#additional-transformations-are-supported-by-numeric-matrices)

- Invert - Returns the inverted matrix or throws an exception if not possible. The current inversion method relies on determinants and as noted, this is only currently feasible for matrices up to 20x20

```
    try {
        $mI = $mA('Invert');
        //same as
        $fInvert = new Chippyash\Math\Matrix\Transformation\Invert();
        $mI = $mA->transform($fInvert);
        //same as
        $mI = $fInvert($mA);
    } catch (Chippyash\Math\Matrix\Exceptions\ComputationException $e) {
        //cannot invert
    }
```

If you want to break the 20x20 limit, you can do the following:

```
    $det = new Chippyash\Math\Matrix\Derivative\Determinant();
    $det->tune('luLimit', 40); //or whatever you are prepared to put up with
    $mI = $mA('Invert');
```

- MarkovRandomWalk - Given a Markov Chain represented as a Numeric Matrix, randomly walk from a start row to a target row, returning a Row Vector Numeric Matrix of IntTypes:

```
    $det = new Chippyash\Math\Matrix\Derivative\MarkovRandomWalk();
    $res = $det->transform(
        $mA,
        array(
            'start'=>TypeFactory::createInt(2),
            'target'=>TypeFactory::createInt(4)
        )
    );
```

You can supply an optional third parameter, `limit` to limit the steps that can be taken. This is set to 100 by default.

```
    $res = $mA(
        'MarkovRandomWalk',
        array(
            'start'=>TypeFactory::createInt(2),
            'target'=>TypeFactory::createInt(4),
            'limit'=>TypeFactory::createInt(10)
        )
    );
```

#### Matrices can be decomposed

[](#matrices-can-be-decomposed)

- The original matrix is untouched
- You can use the magic \_\_invoke functionality
- Decompositions return a decomposition object, from which you can access the various parts of the decomposition.
- Decompositions implement the Chippyash\\Math\\Matrix\\Interfaces\\DecompositionInterface

The library currently supports:

- LU Decomposition
- Gauss Jordan Elimination

**LU**

```
    $lu = $mA('Lu');
    //same as
    $fLu = new Chippyash\Math\Matrix\Decomposition\Lu()
    $lu = $mA->decompose($fLu);
    //same as
    $lu = $fLu($mA);
```

The LU products are:

- LU : NumericMatrix - The LU complete decomposition matrix
- L : NumericMatrix - The lower triangle
- U : NumericMatrix - The upper triangle
- PivotVector : NumericMatrix - Pivot vector of the decomposition
- PermutationMatrix : NumericMatrix - Permutation matrix
- Det : NumericTypeInterface|Null - Determinant or null if matrix is not square

Accessing the products is either via the product() method or more simply as an attribute of the decomposition:

```
    $pv = $lu->product('PivotVector');
    //same as
    $pv = $lu->PivotVector;
```

N.B. Product names for any decomposition are case sensitive

**Gauss Jordan Elimination**

```
    $mA = new NumericMatrix(
                [[1, 1, 1],
                 [2, 3, 5],
                 [4, 0, 5]]
                );
    $mB = new NumericMatrix(
            [[5],
             [8],
             [2]]
            );
    $elim = $mA('GaussJordonElimination', $mB);
    //same as
    $fElim = new Chippyash\Math\Matrix\Decomposition\GaussJordonElimination()
    $elim = $mA->decompose($fElim, $mB);
    //same as
    $elim = $fElim($mA, $mB);
```

The products are:

- left The left matrix after elimination
- right The right matrix after elimination

Using the above example then $elim-&gt;left should == an identity matrix and $elim-&gt;right == \[\[3\],\[4\],\[-2\]\] as we've just solved

```
    x + y + z = 5
    2x + 3y + 5z = 8
    4x + 5z = 2
where
    x = 3, y = 4, z = -2
```

#### Formatting for numeric display

[](#formatting-for-numeric-display)

An additional display formatter is supported by the library:

\\Chippyash\\Math\\Matrix\\Formatter\\AsciiNumeric

It extends the \\Chippyash\\Matrix\\Formatter\\Ascii. An additional option 'outputType' is provided that should take one of the following values:

```
    AsciiNumeric::TP_NONE      //behave as base formatter - default behaviour
    AsciiNumeric::TP_INT       //convert all entries to int.  This will floor() if possible
    AsciiNumeric::TP_FLOAT     //convert all entries to float if possible
    AsciiNumeric::TP_RATIONAL  //convert all entries to rational if possible
    AsciiNumeric::TP_COMPLEX   //convert all entries to complex (always possible)
```

Please note that although you instruct to convert to a particular numeric type the actual display may result in a simpler form if possible.

Example:

```
    echo $mA->setFormatter(new AsciiNumeric())
        ->display(['outputType' => AsciiNumeric::TP_FLOAT]);
```

#### Formatting for a directed graph

[](#formatting-for-a-directed-graph)

To use this functionality you need to include

```
    "clue/graph": "^0.9",
    "graphp/graphviz": "0.2.*"
```

to your composer requires section and run a composer update.

This adds the functionality to use the GraphViz suite of programs to create image files from a NumericMatrix that describes a graph.

The simplest use of the renderer is to simply supply it a NumericMatrix:

```
$mA = new NumericMatrix([[0,0,1],[0,1,0],[1,0,0]]);
$dot = $mA->setFormatter(new DirectedGraph())->display();
```

will produce a GraphViz .dot file content string such as:

```
digraph G {
  0 -> 2 [label=1]
  1 -> 1 [label=1 dir="none"]
  2 -> 0 [label=1]
}
```

Mot often however, you'll want to give some meaning to your vertices. To do this, you can pass in a Monad\\Collection of VertexDescription objects. For example

```
use Monad\Collection;
use Chippyash\Math\Matrix\Formatter\DirectedGraph\VertexDescription;

$attribs = new Collection(
    [
        new VertexDescription(new StringType('A')),
        new VertexDescription(new StringType('B')),
        new VertexDescription(new StringType('C')),
    ]
);
$dot = $mA->setFormatter(new DirectedGraph())->display(['attribs' => $attribs]);
```

gives

```
'digraph G {
  "A" -> "C" [label=1]
  "B" -> "B" [label=1 dir="none"]
  "C" -> "A" [label=1]
}
```

You can also set things like colours and shapes via the VertexDescription. Take a look at the tests.

If you want to do some additional processing prior to generating something through GraphViz, you can pass in an optional parameter:

```
$graph = $mA->setFormatter(new DirectedGraph())->display(['output' => 'object']);
```

will return a Fhaculty\\Graph\\Graph object that you can process further before sending into Graphp\\GraphViz\\GraphViz. You may also want to get a Graph so that you can do some graph processing via the Graphp\\Algorithms library.

Finally, with the DirectedGraph renderer, you can provide an optional callable function that will be applied to the values of the edges. This is often useful to reformat the value in some way. For instance:

```
$mA = new NumericMatrix([[0,50,50],[33,33,33],[100,0,0]]);
$func = function($origValue) {return \round($origValue / 100, 2);};
$dot = $mA->setFormatter(new DirectedGraph())->display(['edgeFunc' => $func]);
```

will produce

```
digraph G {
  0 -> 1 [label=0.5]
  0 -> 2 [label=0.5]
  1 -> 0 [label=0.33]
  1 -> 1 [label=0.33 dir="none"]
  1 -> 2 [label=0.33]
  2 -> 0 [label=1]
}
```

#### Exception handling

[](#exception-handling)

As matrix maths can throw up problems, particularly when inverting or decomposing, it is always a good idea to wrap whatever you are doing in a try - catch block. The following exceptions are supported by the library. They all extend from the Chippyash\\Matrix\\Exceptions\\MatrixException. The base namespace is Chippyash\\Math\\Matrix\\Exceptions

```
  MathMatrixException
  ComputationException
  NoInverseException
  SingularMatrixException
  UndefinedComputationException
  NotMarkovException
```

### Changing the library

[](#changing-the-library)

1. fork it
2. write the test
3. amend it
4. do a pull request

Found a bug you can't figure out?

1. fork it
2. write the test
3. do a pull request

NB. Make sure you rebase to HEAD before your pull request

Where?
------

[](#where)

The library is hosted at [Github](https://github.com/chippyash/Math-Matrix). It is available at [Packagist.org](https://packagist.org/packages/chippyash/math-matrix) as a [Composable](https://getcomposer.org/) module

### Installation

[](#installation)

Install \[Composer\] ()

#### For production

[](#for-production)

add

```
    "chippyash/math-matrix": ">=2,
