rustmatrixiterator

Matrix columns iterator


I am trying to implement the way to get the read-only iterator on columns of the matrix(Vec<Vec<u64>>, not flat, and in real world matrix will be stored differently, but assuming this) in Rust.

It should be similar to this in Python:

>>> m = [[1,2], [3,4]]
>>> list(zip(*m))
[(1, 3), (2, 4)]

I understand in might be complicated due to borrowing rules. But as it is possible to have multiple read-only references at a time, this seems to be possible.


Solution

  • This isn't too complex in Rust.

    pub fn column_iterator<T>(v: &[Vec<T>]) -> impl Iterator<Item = &T> {
        let width = v.first().map(|f| f.len()).unwrap_or(0);
        (0..width).flat_map(|y| v.iter().map(move |row| &row[y]))
    }
    

    For more complex matrix operations, consider using ndarray, which has a columns method.

    use ndarray::{ArrayBase, Data, Ix2};
    
    pub fn column_iterator<'a, T>(
        v: &'a ArrayBase<impl Data<Elem = T>, Ix2>,
    ) -> impl Iterator<Item = &'a T>
    where
        T: 'a,
    {
        v.columns().into_iter().flatten()
    }