nalgebra icon indicating copy to clipboard operation
nalgebra copied to clipboard

Add method to convert a Matrix into a Vec.

Open sebcrozet opened this issue 7 years ago • 4 comments

See https://github.com/rustsim/nalgebra/issues/473#issuecomment-440038489

The goal is to add an .into_vec method that would either unwrap the underlying Vec storage, or would perform a copy if the storage is not MatrixVec.

Note that one way of achieving this would be to add an implementation of IntoIter for Matrix. Then the matrix.into_iter().collect() will do the trick and will not perform any copy for matrices with a MatrixVec storage because of that optimization.

sebcrozet avatar Nov 19 '18 21:11 sebcrozet

Note that one way of achieving this would be to add an implementation of IntoIter for Matrix.

Confusingly, this already sort of exists, but doesn't appear in the rendered rustdoc.

So, a generic-but-inefficient conversion implementation would be:

#[cfg(any(feature = "std", feature = "alloc"))]
impl<N, R, C, S> Into<Vec<N>> for Matrix<N, R, C, S>
where
    N: Scalar,
    R: Dim,
    C: Dim,
    S: Storage<N, R, C>,
{
    fn into(self) -> Vec<N> {
        use std::iter::FromIterator;
        Vec::from_iter(self.into_iter().cloned())
    }
}

The .cloned() is needed because self.into_iter() produces an iterator of references; that's a consequence of the fact that IntoIterator is only implemented for &Matrix. Implementing IntoIterator for Matrix where type IntoIter = MatrixIter isn't possible. At any rate, doing so wouldn't actual enable that optimization since that optimization only applies to vec::IntoIter.

jswrenn avatar Nov 20 '18 22:11 jswrenn

I'm also interested in this feature.

Why isn't it possible to implement IntoIterator for Matrix where type IntoIter = MatrixIter? It should be possible to convert the underlying Vec storage into an Iterator, right?

luiswirth avatar Oct 11 '20 12:10 luiswirth

Implementing .into_vec would actually be very simple, because there already exists Into<Vec<N>> for MatrixVec<N, R, C> since #481. So IntoIterator should be easy too, right?

luiswirth avatar Oct 11 '20 12:10 luiswirth

is this issue still open?

pradkrish avatar Nov 12 '21 17:11 pradkrish