dimforge / nalgebra

Linear algebra library for Rust.
https://nalgebra.org
Apache License 2.0
3.94k stars 469 forks source link

Add method to convert a Matrix into a Vec. #479

Open sebcrozet opened 5 years ago

sebcrozet commented 5 years ago

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.

jswrenn commented 5 years ago

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.

luiswirth commented 3 years ago

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 commented 3 years ago

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?

pradkrish commented 2 years ago

is this issue still open?