nalgebra icon indicating copy to clipboard operation
nalgebra copied to clipboard

[bug] Reshape does not work with views

Open Danvil opened this issue 2 years ago • 4 comments

In my use case I take a (sub-)view of a matrix and then reshape that view. Unfortunately that gives wrong results and reshape does not take the view into account.

Here is an example which shows the failure:

fn test_shape() {
    let m1 = nalgebra::DMatrix::from_row_slice(
        3,
        4,
        &[
            1.0, 2.0, 3.0, 4.0, //
            5.0, 6.0, 7.0, 8.0, //
            9.0, 10.0, 11.0, 12.0, //
        ],
    );

    let m2 = m1.view((0, 0), (2, 3));

    let m3 = m2.reshape_generic(nalgebra::Dyn(6), nalgebra::Dyn(1));

    assert_eq!(m3[(0, 0)], 1.0);
    assert_eq!(m3[(1, 0)], 5.0);
    assert_eq!(m3[(2, 0)], 2.0);  // it's 9 instead
    assert_eq!(m3[(3, 0)], 6.0);  // it's 2 instead
    assert_eq!(m3[(4, 0)], 3.0);  // it's 6 instead
    assert_eq!(m3[(5, 0)], 7.0);  // it's 10 instead
}

Danvil avatar Feb 06 '23 00:02 Danvil

Ah, damn, this is my fault. I think when I recently implemented ReshapableStorage for views, I didn't properly account for strides in cases like this. Thanks a lot for the report, I hope I will find time soon to look into this (this week or next), should hopefully be a quick fix (with some more exhaustive testing).

Andlon avatar Feb 06 '23 12:02 Andlon

@Andlon Thank you for the quick reply and happy to hear you already know what is wrong. I would be happy to help, but very new to nalgebra.

Also btw is there a reason why the function is called reshape_generic instead of just reshape? In combination with this bug I had a hard time figuring out if I am supposed to use this function or not :)

Danvil avatar Feb 06 '23 17:02 Danvil

Hello! I would like to take a look and see if i can fix it :)

zFishStick avatar Oct 12 '25 11:10 zFishStick

Hello @Andlon , i would like to solve the issue but i'm a bit lost. Did you managed to figure out a possible solution?

zFishStick avatar Oct 13 '25 20:10 zFishStick