Ndarray delete rows

Hi guys,

I have a 2d matrix of type ndarray::Array2, named matrix, and another vector named vec, vec contains all the indices of rows in matrix that need to be tossed.

I now need a new matrix, which contains all the rows except whose indices is in vec.

How should I do it gracefully?

Best,
Tori

Hi,

I don't have much experience with the ndarray crate, but I would suggest using an iterator to filter to rows you want to keep. Something around those lines.

extern crate ndarray;
use ndarray::{Array, Array2, Axis};
use std::iter::FromIterator;

fn remove_rows<A: Clone>(matrix: &Array2<A>, to_remove: &[usize]) -> Array2<A> {
    let mut keep_row = vec![true; matrix.nrows()];
    to_remove.iter().for_each(|row| keep_row[*row] = false);

    let elements_iter = matrix
        .axis_iter(Axis(0))
        .zip(keep_row.iter())
        .filter(|(_row, keep)| **keep)
        .flat_map(|(row, _keep)| row.to_vec());

    let new_n_rows = matrix.nrows() - to_remove.len();
    Array::from_iter(elements_iter)
        .into_shape((new_n_rows, matrix.ncols()))
        .unwrap()
}

fn main() {
    let matrix = Array::from_iter(0..15).into_shape((5, 3)).unwrap();
    println!("Full matrix:\n {}", matrix);

    let submatrix = remove_rows(&matrix, &[0, 3]);
    println!("Submatrix:\n {}", submatrix);
}