0

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.] ]
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
daniellga
  • 1,142
  • 6
  • 16
  • 2
    If these are matrices, you could save a lot of work by using one of the many [matrix](https://lib.rs/keywords/matrix)/[linear algebra](https://lib.rs/keywords/algebra) crates in the ecosystem. – John Kugelman Mar 08 '22 at 21:25

1 Answers1

3

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366