Skip to content

Question: Swap rows/columns idiomatically in ndarray #1005

@skailasa

Description

@skailasa

I'd like to swap the rows/columns of a given 2D ndarray idiomatically. I've found this question: #545, which explains that one can create two mutable array views, however it doesn't explain how this is done. I've done something hacky, like so,

fn swap(mut keys: KeysViewMut, i: usize, j: usize) {

    let mut row_x = keys.index_axis_mut(ndarray::Axis(0), 0);
    row_x.swap(i, j);
    {
        let mut row_y = keys.index_axis_mut(ndarray::Axis(0), 1);
        row_y.swap(i, j);
    }
    {
        let mut row_z = keys.index_axis_mut(ndarray::Axis(0), 2);
        row_z.swap(i, j);
    }
    {
        let mut row_l = keys.index_axis_mut(ndarray::Axis(0), 3);
        row_l.swap(i, j);
    }
}

To ensure that the borrows are in their own scope.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions