Skip to main content

08_slicing_builder/
08_slicing_builder.rs

1//! The canonical slicing API: builder with `.all()`, `.index()`, `.range()`.
2//!
3//! Run: cargo run --example 08_slicing_builder
4//!
5//! The builder is the canonical form; `slice_str` is a convenience wrapper.
6
7use matten::Tensor;
8
9fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let t = Tensor::new((1..=12).map(|x| x as f64).collect(), &[3, 4]);
11    println!("tensor   {t:?}");
12
13    // First row (index 0, axis removed from output shape)
14    let row0 = t.slice().index(0).all().build()?;
15    println!("row 0    {row0:?}"); // shape [4]
16
17    // First two rows, all columns
18    let top2 = t.slice().range(0..2).all().build()?;
19    println!("top 2    {top2:?}"); // shape [2,4]
20
21    // All rows, columns 1..3
22    let cols = t.slice().all().range(1..3).build()?;
23    println!("cols 1:3 {cols:?}"); // shape [3,2]
24
25    // Single element -> scalar
26    let elem = t.slice().index(1).index(2).build()?;
27    assert!(elem.is_scalar());
28    println!("t[1,2]   {elem:?}");
29
30    Ok(())
31}