Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum elements of Vec<Vec<f64>> together into a Vec<f64>?

Tags:

rust

I am looking for an "rusty" way to accumulate a Vec<Vec> into a Vec such that the 1st element of every inner Vec is summed together, every 2nd element of each Vec is summed together, etc..., and the results are collected into a Vec? If I just use sum(), fold(), or accumulate() I believe I will sum entire 1st Vec together into a single element, rather than the 1st element of each inner Vec contained in the 2D Vec.

pub fn main() {
    let v1 = vec![1.1, 2.2, 3.3];
    let vv = vec![v1; 3];
    let desired_result = vec![3.3, 6.6, 9.9];
}
like image 272
Matthew Pittenger Avatar asked Oct 23 '25 17:10

Matthew Pittenger


1 Answers

Sometimes it's easy to forget in Rust that the imperative approach exists and is an easy solution.

let mut sums = vec![0.0; vv[0].len()];
for v in vv {
    for (i, x) in v.into_iter().enumerate() {
        sums[i] += x;
    }
}
like image 107
orlp Avatar answered Oct 26 '25 09:10

orlp