Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I concatenate many Vec<Vec<f64>> to produce another Vec<Vec<f64>>?

Is there an easy and optimal way to combine a and b to get c? I am struggling with this since I can’t use index for c because it’s not initialized. I am trying to avoid initializing c using 2 vectors of zeroes.

let mut a: Vec<Vec<f64>> = Vec::with_capacity(2);

a.push(vec![1., 2., 3.]);
a.push(vec![4., 5., 6.]);

let mut b: Vec<Vec<f64>> = Vec::with_capacity(2);

b.push(vec![7., 8., 9.]);
b.push(vec![10., 11., 12.]);

let mut c: Vec<Vec<f64>> = Vec::with_capacity(2);

// expected result:
// c: Vec<Vec<f64>> = [[1., 2., 3., 7., 8., 9.], [4., 5., 6., 10., 11., 12.] ]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There a large number of ways to do this. One is to zip the outer vectors and then concatenate the inner vectors:

let a: Vec<Vec<f64>> = vec![vec![1., 2., 3.], vec![4., 5., 6.]];

let b: Vec<Vec<f64>> = vec![vec![7., 8., 9.], vec![10., 11., 12.]];

let c: Vec<Vec<f64>> = a
    .into_iter()
    .zip(b)
    .map(|(mut a, b)| {
        a.extend(b);
        a
    })
    .collect();

assert_eq!(c, [[1., 2., 3., 7., 8., 9.], [4., 5., 6., 10., 11., 12.]]);

See also:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading