ruststructiteratornalgebra

Flatten and combine field from nested struct


I have a struct body struct that contains planet info such as position velocity etc

pub struct Body {
    pub id: u8,
    pub pos: Vec<f64>,
    pub vel: Vec<f64>,
}

pub struct Data {
    pub system_vec: Vec<Body>,
}

To put all the pos/vel vecs into a nalgebra matrix I need to first flatten all the body vecs into an iterator I can feed to the nalgebra api.

let ncols: &usize = &self.system_vec.len();
let temp_vec = &data.system_vec
                    .iter()
                    .map(|body| body.pos.clone())
                    .collect::<Vec<Vec<f64>>>()
                    .into_iter()
                    .flatten()
                    .collect::<Vec<f64>>();

na::OMatrix::<f64, U3, Dyn>::from_iterator(
    *ncols, 
    temp_vec.iter().cloned()
)

My question is this seems to be incredibly over engineered. I'm iterating and then collecting and then iterating again. I'm sure there is a better way but I'm quite new to rust so this is the best I've got so far. Is there a more efficient way to get a cloned version of this data into the matrix?


Solution

  • I've found a more streamlined solution -

    let temp_vec = &self.system_vec
                   .iter()
                   .flat_map(|body| body.pos.clone().into_iter())
                   .collect::<Vec<f64>>();