I am learning the rust language and working with the ndarray crate. Could someone explain to me how to apply cumulative functions to an ndarray?
As example it would be great to see how to get a cumulative product of an ndarray.
I could not manage to find any higher level function here for this, like numpy offers numpy.cumprod()
I came up whith this, is there a faster/better way in rust with ndarray, can vectorization be used for cumulative functions?
let some_valuesvalues = Array1::from(vec![2.0, 3.0, 4.0, 5.0]);
let cumulative_products: Array1<f64> = some_values
.iter()
.scan(1.0, |acc, &x| {
*acc *= x;
Some(*acc)
})
.collect();
There is no benefit in packing the vector into an Array1
beforehand. You can do this after the calculation.
If you already have an Array1
convert it to the inner vector with to_vec()
.
You can reuse the vector some_values
to store the cumulative_products
results:
let mut some_values = vec![2.0, 3.0, 4.0, 5.0];
let cumulative_products = &mut some_values[..];
let mut last = 1_f64;
for i in 0..cumulative_products.len() {
last *= cumulative_products[i];
cumulative_products[i] = last;
}
gets: [2.0, 6.0, 24.0, 120.0]