markrogoyski / math-php

Powerful modern math library for PHP: Features descriptive statistics and regressions; Continuous and discrete probability distributions; Linear algebra with matrices and vectors, Numerical analysis; special mathematical functions; Algebra
MIT License
2.32k stars 238 forks source link

Add row/column algebra methods to Matrix for Vector #459

Open Aweptimum opened 1 year ago

Aweptimum commented 1 year ago

This request doesn't really have any justification in the pure linear algebra world, but I have run into a use case where I want to treat 3 columns of a 3x3 matrix as vectors. This 3x3 matrix is constructed from 3 column vectors so that I can easily multiply it by another 3x3 rotation matrix (rotating the 3 vectors in one operation). The issue is that I'd still like to operate on the individual columns of the matrix. It would be convenient if there were methods similar to the columnAdd/rowAdd methods and friends that took a row/column index and a vector as arguments.

$mat = MatrixFactory::createIdentity(3);
$displacement = new Vector([2,0,0]);
$mat  = $mat->columnAdd(0, $displacement);
var_dump($mat->getColumn(0)) // prints [3,0,0]

Currently I'm doing this instead:

$mat = MatrixFactory::createIdentity(3);
$zero = new Vector([0,0,0]);
$displacement = new Vector([2,0,0]);
$displacementMat = MatrixFactory::createFromVectors([
    $displacement, $zero, $zero
]);
$mat = $mat->add($displacementMat);

Which isn't much more trouble to write, it's just less clear what's going on.

Understandable if it's preferred to not add these kinds of methods.

markrogoyski commented 1 year ago

Hi @Aweptimum,

Thank you for your interest in MathPHP.

If I understand the request, it would be something like a new Matrix function called columnAddVector that:

Example

    | 1 1 1 |       | 1 |
M = | 2 2 2 |   V = | 2 |
    | 3 3 3 |       | 3 |

$R = $M->columnAddVector(0, $V);

    | 2 1 1 |
R = | 4 2 2 |
    | 6 3 3 |

And there would be equivalent ones for a row add as well.

Does that capture the intent of the feature request?

Aweptimum commented 1 year ago

Yes, it captures it perfectly 👍

Aweptimum commented 1 year ago

Forgot to mention I might have the time to implement this myself next Friday if you approve of the feature