Skip to main content

56_rolling_windows_basic/
56_rolling_windows_basic.rs

1//! Rolling window operations: sum and max over overlapping slices.
2//!
3//! Run: cargo run --example 56_rolling_windows_basic
4
5use matten::Tensor;
6
7fn rolling_sum(t: &Tensor, window: usize) -> Vec<f64> {
8    (0..=(t.len() - window))
9        .map(|i| t.slice().range(i..i + window).build().unwrap().sum())
10        .collect()
11}
12
13fn rolling_max(t: &Tensor, window: usize) -> Vec<f64> {
14    (0..=(t.len() - window))
15        .map(|i| t.slice().range(i..i + window).build().unwrap().max())
16        .collect()
17}
18
19fn main() {
20    let series = Tensor::from_vec(vec![3.0, 1.0, 4.0, 1.0, 5.0, 9.0, 2.0, 6.0]);
21    let w = 3;
22
23    let sums = rolling_sum(&series, w);
24    let maxes = rolling_max(&series, w);
25
26    println!("series       = {:?}", series.as_slice());
27    println!("rolling sum  = {:?}", sums);
28    println!("rolling max  = {:?}", maxes);
29
30    assert_eq!(sums[0], 8.0); // 3+1+4
31    assert_eq!(maxes[0], 4.0); // max(3,1,4)
32    println!("Rolling windows: OK");
33}