dimforge / nalgebra

Linear algebra library for Rust.
https://nalgebra.org
Apache License 2.0
3.94k stars 468 forks source link

Inconsistency between Numpy/MATLAB and and nalgebra #1374

Closed Ruhrpottpatriot closed 5 months ago

Ruhrpottpatriot commented 6 months ago

Take the following two matrices

F = [
    [1.0, 0.0,5.0,0.0,12.5,0.0],
    [0.0, 1.0, 0.0, 5.0, 0.0, 12.5],
    [0.0, 0.0, 1.0, 0.0, 5.0, 0.0],
    [0.0, 0.0, 0.0, 1.0, 0.0, 5.0],
    [0.0, 0.0, 0.0, 0.0, 0.92, 0.0],
    [0.0, 0.0,0.0,0.0,0.0,0.92]
]

and

pkk = [
    [2500.0, 0.0, 0.0, 0.0, 0.0, 0.0],
    [0.0, 2500.0, 0.0, 0.0, 0.0, 0.0],
    [0.0, 0.0, 335.41, 0.0, 0.0, 0.0],
    [0.0, 0.0, 0.0, 335.41, 0.0, 0.0],
    [0.0, 0.0, 0.0, 0.0, 9.14, 0.0],
    [0.0, 0.0, 0.0, 0.0, 0.0, 9.14]
]

Multiplying the two matrices by calculating yields different results than both numpy and MATLAB, i.e. the operation F * pkk in MATLAB, respectively F.dot(pkk) in numpy, both return

F.dot(pkk) == [
    [2500.0, 0.0, 1677.05, 0.0, 114.20, 0.0],
    [0.0, 2500.0, 0.0, 1677.05, 0.0, 114.20],
    [0.0, 0.0, 335.41, 0.0, 45.68, 0.0],
    [0.0, 0.0, 0.0, 335.41, 0.0, 45.68],
    [0.0, 0.0, 0.0, 0.0, 8.40, 0.0],
    [0.0, 0.0, 0.0, 0.0, 0.0, 8.40]
]

whereas the same operation in nalgebra yields

F * pkk == [
    [2500.0, 0.0,12500.0, 0.0, 31250.0, 0.0],
    [0.0, 2500.0, 0.0, 12500.0, 0.0, 31250.0],
    [0.0, 0.0, 335.41, 0.0, 1677.05, 0.0],
    [0.0, 0.0, 0.0, 335.41, 0.0, 1677.05],
    [0.0, 0.0, 0.0, 0.0, 8.40, 0.0],
    [0.0, 0.0, 0.0, 0.0, 0.0, 8.40]
]

However, flipping the arguments, i.e. calculating pkk * F yields the correct result, even in nalgebra.

Is this the intended behaviour? Doing calculations different that two of the most widespread linalg tools seems very counter-intuitive to me.

Ralith commented 6 months ago

Matrix multiplication isn't commutative. If switching the order makes your result correct, that usually means you have something transposed. I don't know numpy or MATLAB, and you haven't shared the exact nalgebra code you used, but you should make certain that you haven't inadvertently swapped rows with columns when constructing a matrix in one case or the other.

Andlon commented 5 months ago

Closing since it's not reproducible without example code. Matrix multiplication is very well-tested in nalgebra, so unless we have some code I'm inclined to think it's an issue of accidental transposition or similar user error, as @Ralith suggested.

Feel free to get back to us with a code example that shows the issue, however, and I will re-open.