NdArray

Struct NdArray 

Source
pub struct NdArray<D>(/* private fields */);

Implementations§

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn dims0(&self) -> Result<()>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn dims1(&self) -> Result<usize>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn dims2(&self) -> Result<(usize, usize)>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn dims3(&self) -> Result<(usize, usize, usize)>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn dims4(&self) -> Result<(usize, usize, usize, usize)>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn dims5(&self) -> Result<(usize, usize, usize, usize, usize)>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn new<A: ToNdArray<T>>(array: A) -> Result<Self>

Creates a new NdArray from any supported Rust array or slice.

use numrst::NdArray;

let a = NdArray::new(&[1, 2, 3]).unwrap();
println!("{}", a.shape());
Examples found in repository?
examples/nrst.rs (line 9)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let tmpfile = NamedTempFile::new().unwrap();
8
9    let scalar = NdArray::new(1).unwrap();
10    let vector_f32 = NdArray::new(&[1.0f32, 2., 3.]).unwrap();
11    let matrix_f32 = NdArray::new(&[[1, 2, 3], [3, 4, 5]]).unwrap();
12    let ones_f32 = NdArray::<f32>::ones((2, 9)).unwrap();
13    let randn_f64 = NdArray::randn(0.0f64, 1., (1, 2, 3)).unwrap();
14    let fill_f64 = NdArray::full((2, 3, 4), 1.2).unwrap();
15    let arange_f64 = NdArray::arange(0., 10.).unwrap();
16    let trues = NdArray::trues((3, 4)).unwrap();
17    let booleans = NdArray::new(&[[true, false], [false, true]]).unwrap();
18
19
20    let mut ndarrays = HashMap::new();
21    ndarrays.insert("scalar".to_string(), DynamicNdArray::I32(scalar));
22    ndarrays.insert("vector_f32".to_string(), DynamicNdArray::F32(vector_f32));
23    ndarrays.insert("matrix_f32".to_string(), DynamicNdArray::I32(matrix_f32));
24    ndarrays.insert("ones_f32".to_string(), DynamicNdArray::F32(ones_f32));
25    ndarrays.insert("randn_f64".to_string(), DynamicNdArray::F64(randn_f64));
26    ndarrays.insert("fill_f64".to_string(), DynamicNdArray::F64(fill_f64));
27    ndarrays.insert("arange_f64".to_string(), DynamicNdArray::F64(arange_f64));
28    ndarrays.insert("trues".to_string(), DynamicNdArray::Bool(trues));
29    ndarrays.insert("booleans".to_string(), DynamicNdArray::Bool(booleans));
30
31    numrst::io::save_zfile(&ndarrays, tmpfile.path()).unwrap();
32
33    let ndarrays = numrst::io::load_zfile(tmpfile.path()).unwrap();
34    for (name, _) in ndarrays {
35        println!("{}", name);
36    }
37    Ok(())
38}
More examples
Hide additional examples
examples/npy.rs (line 9)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let tmpfile = NamedTempFile::new().unwrap();
8
9    let scalar = NdArray::new(1).unwrap();
10    let vector_f32 = NdArray::new(&[1.0f32, 2., 3.]).unwrap();
11    let matrix_f32 = NdArray::new(&[[1, 2, 3], [3, 4, 5]]).unwrap();
12    let ones_f32 = NdArray::<f32>::ones((2, 9)).unwrap();
13    let randn_f64 = NdArray::randn(0.0f64, 1., (1, 2, 3)).unwrap();
14    let fill_f64 = NdArray::full((2, 3, 4), 1.2).unwrap();
15    let arange_f64 = NdArray::arange(0., 10.).unwrap();
16    let trues = NdArray::trues((3, 4)).unwrap();
17    let booleans = NdArray::new(&[[true, false], [false, true]]).unwrap();
18
19    let mut ndarrays = HashMap::new();
20    ndarrays.insert("scalar".to_string(), DynamicNdArray::I32(scalar));
21    ndarrays.insert("vector_f32".to_string(), DynamicNdArray::F32(vector_f32));
22    ndarrays.insert("matrix_f32".to_string(), DynamicNdArray::I32(matrix_f32));
23    ndarrays.insert("ones_f32".to_string(), DynamicNdArray::F32(ones_f32));
24    ndarrays.insert("randn_f64".to_string(), DynamicNdArray::F64(randn_f64));
25    ndarrays.insert("fill_f64".to_string(), DynamicNdArray::F64(fill_f64));
26    ndarrays.insert("arange_f64".to_string(), DynamicNdArray::F64(arange_f64));
27    ndarrays.insert("trues".to_string(), DynamicNdArray::Bool(trues));
28    ndarrays.insert("booleans".to_string(), DynamicNdArray::Bool(booleans));
29
30    numrst::io::save_npz_file(&ndarrays, tmpfile.path()).unwrap();
31
32    let ndarrays = numrst::io::load_npz_file(tmpfile.path()).unwrap();
33    for (name, _) in ndarrays {
34        println!("{}", name);
35    }
36
37    Ok(())
38}
Source

pub fn full<S: Into<Shape>>(shape: S, value: T) -> Result<Self>

Creates an array full with a constant value.

use numrst::NdArray;

let a = NdArray::full((2, 2), 7).unwrap();
println!("{}", a);
Examples found in repository?
examples/arithmetic.rs (line 5)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let a = NdArray::<f32>::ones((2, 2))?;
5    let b = NdArray::<f32>::full((2, 2), 2.0)?;
6
7    let c = a.add(&b)?;
8    let d = b.sub(&a)?;
9    let e = b.mul(&c)?;
10    let f = e.div(&d)?;
11
12    println!("a:\n{:?}", a);
13    println!("b:\n{}", b);
14    println!("a + b:\n{}", c);
15    println!("b - a:\n{:?}", d);
16    println!("b * (a + b):\n{}", e);
17    println!("e / d:\n{}", f);
18
19    Ok(())
20}
More examples
Hide additional examples
examples/logic.rs (line 6)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
examples/nrst.rs (line 14)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let tmpfile = NamedTempFile::new().unwrap();
8
9    let scalar = NdArray::new(1).unwrap();
10    let vector_f32 = NdArray::new(&[1.0f32, 2., 3.]).unwrap();
11    let matrix_f32 = NdArray::new(&[[1, 2, 3], [3, 4, 5]]).unwrap();
12    let ones_f32 = NdArray::<f32>::ones((2, 9)).unwrap();
13    let randn_f64 = NdArray::randn(0.0f64, 1., (1, 2, 3)).unwrap();
14    let fill_f64 = NdArray::full((2, 3, 4), 1.2).unwrap();
15    let arange_f64 = NdArray::arange(0., 10.).unwrap();
16    let trues = NdArray::trues((3, 4)).unwrap();
17    let booleans = NdArray::new(&[[true, false], [false, true]]).unwrap();
18
19
20    let mut ndarrays = HashMap::new();
21    ndarrays.insert("scalar".to_string(), DynamicNdArray::I32(scalar));
22    ndarrays.insert("vector_f32".to_string(), DynamicNdArray::F32(vector_f32));
23    ndarrays.insert("matrix_f32".to_string(), DynamicNdArray::I32(matrix_f32));
24    ndarrays.insert("ones_f32".to_string(), DynamicNdArray::F32(ones_f32));
25    ndarrays.insert("randn_f64".to_string(), DynamicNdArray::F64(randn_f64));
26    ndarrays.insert("fill_f64".to_string(), DynamicNdArray::F64(fill_f64));
27    ndarrays.insert("arange_f64".to_string(), DynamicNdArray::F64(arange_f64));
28    ndarrays.insert("trues".to_string(), DynamicNdArray::Bool(trues));
29    ndarrays.insert("booleans".to_string(), DynamicNdArray::Bool(booleans));
30
31    numrst::io::save_zfile(&ndarrays, tmpfile.path()).unwrap();
32
33    let ndarrays = numrst::io::load_zfile(tmpfile.path()).unwrap();
34    for (name, _) in ndarrays {
35        println!("{}", name);
36    }
37    Ok(())
38}
examples/npy.rs (line 14)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let tmpfile = NamedTempFile::new().unwrap();
8
9    let scalar = NdArray::new(1).unwrap();
10    let vector_f32 = NdArray::new(&[1.0f32, 2., 3.]).unwrap();
11    let matrix_f32 = NdArray::new(&[[1, 2, 3], [3, 4, 5]]).unwrap();
12    let ones_f32 = NdArray::<f32>::ones((2, 9)).unwrap();
13    let randn_f64 = NdArray::randn(0.0f64, 1., (1, 2, 3)).unwrap();
14    let fill_f64 = NdArray::full((2, 3, 4), 1.2).unwrap();
15    let arange_f64 = NdArray::arange(0., 10.).unwrap();
16    let trues = NdArray::trues((3, 4)).unwrap();
17    let booleans = NdArray::new(&[[true, false], [false, true]]).unwrap();
18
19    let mut ndarrays = HashMap::new();
20    ndarrays.insert("scalar".to_string(), DynamicNdArray::I32(scalar));
21    ndarrays.insert("vector_f32".to_string(), DynamicNdArray::F32(vector_f32));
22    ndarrays.insert("matrix_f32".to_string(), DynamicNdArray::I32(matrix_f32));
23    ndarrays.insert("ones_f32".to_string(), DynamicNdArray::F32(ones_f32));
24    ndarrays.insert("randn_f64".to_string(), DynamicNdArray::F64(randn_f64));
25    ndarrays.insert("fill_f64".to_string(), DynamicNdArray::F64(fill_f64));
26    ndarrays.insert("arange_f64".to_string(), DynamicNdArray::F64(arange_f64));
27    ndarrays.insert("trues".to_string(), DynamicNdArray::Bool(trues));
28    ndarrays.insert("booleans".to_string(), DynamicNdArray::Bool(booleans));
29
30    numrst::io::save_npz_file(&ndarrays, tmpfile.path()).unwrap();
31
32    let ndarrays = numrst::io::load_npz_file(tmpfile.path()).unwrap();
33    for (name, _) in ndarrays {
34        println!("{}", name);
35    }
36
37    Ok(())
38}
examples/shape.rs (line 34)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Reshape ---
5    let a = NdArray::<i32>::arange(0, 12)?;
6    let a2d = a.reshape((3, 4))?;
7    let a3d = a.reshape((2, 2, 3))?;
8
9    println!("Original a (1D):\n{}", a);
10    println!("Reshaped a (3x4):\n{}", a2d);
11    println!("Reshaped a (2x2x3):\n{}", a3d);
12
13    // --- Transpose ---
14    let t = a2d.transpose(0, 1)?;
15    println!("Transpose a2d (swap dim 0 <-> 1):\n{}", t);
16
17    // --- Unsqueeze & Squeeze ---
18    let b = NdArray::<f32>::arange(0.0, 6.0)?.reshape((2, 3))?;
19    let b_unsq = b.unsqueeze(0)?; // add axis at front -> (1,2,3)
20    let b_sq = b_unsq.squeeze(0)?; // remove axis -> (2,3)
21
22    println!("b shape: {}", b.shape());
23    println!("b_unsq shape: {}", b_unsq.shape());
24    println!("b_sq shape: {}", b_sq.shape());
25
26    // --- Narrow & Narrow Range ---
27    let narrowed = b.narrow(1, 0, 2)?; // take first 2 cols along axis 1
28    let narrowed_range = b.narrow_range(1, &rng!(0:2))?;
29
30    println!("narrowed (axis=1, first 2 cols):\n{}", narrowed);
31    println!("narrowed_range (axis=1, 0..2):\n{}", narrowed_range);
32
33    // --- Concatenate ---
34    let c1 = NdArray::<i32>::full((2, 2), 1)?;
35    let c2 = NdArray::<i32>::full((2, 2), 2)?;
36    let cat = NdArray::cat(&[&c1, &c2], 0)?; // concat along axis=0
37
38    println!("Concatenate along axis=0:\n{}", cat);
39
40    // --- Stack ---
41    let s1 = NdArray::<i32>::full((2, 2), 3)?;
42    let s2 = NdArray::<i32>::full((2, 2), 4)?;
43    let stacked = NdArray::stack(&[&s1, &s2], 0)?; // stack new axis
44
45    println!("Stacked along new axis=0:\n{}", stacked);
46
47    Ok(())
48}
Source§

impl<T: NumDType> NdArray<T>

Source

pub fn zeros<S: Into<Shape>>(shape: S) -> Result<Self>

Creates an array of zeros with the given shape.

use numrst::NdArray;

let a = NdArray::<f32>::zeros((2, 3)).unwrap();
println!("{}", a);
Examples found in repository?
examples/view.rs (line 4)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let total = NdArray::<f32>::zeros((5, 5)).unwrap();
5
6    {
7        let mut sub = total.index((1..3, 2..4)).unwrap();
8        let source = sub.randn_like(0.0, 1.0).unwrap();
9        let mut sub_view = sub.matrix_view_mut().unwrap();
10
11        sub_view.copy_from(&source).unwrap();
12    }
13    
14    println!("{}", total);
15
16    Ok(())
17}
More examples
Hide additional examples
examples/construct.rs (line 5)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // Create arrays with different constructors
5    let zeros = NdArray::<f32>::zeros((2, 3))?;
6    let ones = NdArray::<f32>::ones((2, 3))?;
7    let arange = NdArray::<i32>::arange(0, 10)?;
8    let rand = NdArray::<f32>::rand(0.0, 1.0, (2, 5, 3, 4))?;
9    let randn = NdArray::<f32>::randn(0.0, 1.0, (2, 2))?;
10
11    println!("zeros:\n{}", zeros);
12    println!("ones:\n{}", ones);
13    println!("arange:\n{}", arange);
14    println!("rand:\n{}", rand);
15    println!("randn:\n{}", randn);
16
17    Ok(())
18}
Source

pub fn zero_like(&self) -> Result<Self>

Creates a zero-filled array with the same shape as self.

use numrst::NdArray;

let a = NdArray::<i32>::ones((2, 2)).unwrap();
let b = a.zero_like().unwrap();
println!("{}", b);
Source

pub fn ones<S: Into<Shape>>(shape: S) -> Result<Self>

Creates an array of ones with the given shape.

use numrst::NdArray;

let a = NdArray::<f64>::ones((3, 3)).unwrap();
println!("{}", a);
Examples found in repository?
examples/broadcasting.rs (line 4)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let a = NdArray::<f32>::ones((3, 3))?;
5    let b = NdArray::<f32>::arange(0.0, 3.0)?.reshape((3, 1))?;
6
7    let c = a.broadcast_add(&b)?; // broadcasting
8    println!("a:\n{}", a);
9    println!("b:\n{}", b);
10    println!("a + b (broadcast):\n{}", c);
11
12    Ok(())
13}
More examples
Hide additional examples
examples/arithmetic.rs (line 4)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let a = NdArray::<f32>::ones((2, 2))?;
5    let b = NdArray::<f32>::full((2, 2), 2.0)?;
6
7    let c = a.add(&b)?;
8    let d = b.sub(&a)?;
9    let e = b.mul(&c)?;
10    let f = e.div(&d)?;
11
12    println!("a:\n{:?}", a);
13    println!("b:\n{}", b);
14    println!("a + b:\n{}", c);
15    println!("b - a:\n{:?}", d);
16    println!("b * (a + b):\n{}", e);
17    println!("e / d:\n{}", f);
18
19    Ok(())
20}
examples/construct.rs (line 6)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // Create arrays with different constructors
5    let zeros = NdArray::<f32>::zeros((2, 3))?;
6    let ones = NdArray::<f32>::ones((2, 3))?;
7    let arange = NdArray::<i32>::arange(0, 10)?;
8    let rand = NdArray::<f32>::rand(0.0, 1.0, (2, 5, 3, 4))?;
9    let randn = NdArray::<f32>::randn(0.0, 1.0, (2, 2))?;
10
11    println!("zeros:\n{}", zeros);
12    println!("ones:\n{}", ones);
13    println!("arange:\n{}", arange);
14    println!("rand:\n{}", rand);
15    println!("randn:\n{}", randn);
16
17    Ok(())
18}
examples/nrst.rs (line 12)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let tmpfile = NamedTempFile::new().unwrap();
8
9    let scalar = NdArray::new(1).unwrap();
10    let vector_f32 = NdArray::new(&[1.0f32, 2., 3.]).unwrap();
11    let matrix_f32 = NdArray::new(&[[1, 2, 3], [3, 4, 5]]).unwrap();
12    let ones_f32 = NdArray::<f32>::ones((2, 9)).unwrap();
13    let randn_f64 = NdArray::randn(0.0f64, 1., (1, 2, 3)).unwrap();
14    let fill_f64 = NdArray::full((2, 3, 4), 1.2).unwrap();
15    let arange_f64 = NdArray::arange(0., 10.).unwrap();
16    let trues = NdArray::trues((3, 4)).unwrap();
17    let booleans = NdArray::new(&[[true, false], [false, true]]).unwrap();
18
19
20    let mut ndarrays = HashMap::new();
21    ndarrays.insert("scalar".to_string(), DynamicNdArray::I32(scalar));
22    ndarrays.insert("vector_f32".to_string(), DynamicNdArray::F32(vector_f32));
23    ndarrays.insert("matrix_f32".to_string(), DynamicNdArray::I32(matrix_f32));
24    ndarrays.insert("ones_f32".to_string(), DynamicNdArray::F32(ones_f32));
25    ndarrays.insert("randn_f64".to_string(), DynamicNdArray::F64(randn_f64));
26    ndarrays.insert("fill_f64".to_string(), DynamicNdArray::F64(fill_f64));
27    ndarrays.insert("arange_f64".to_string(), DynamicNdArray::F64(arange_f64));
28    ndarrays.insert("trues".to_string(), DynamicNdArray::Bool(trues));
29    ndarrays.insert("booleans".to_string(), DynamicNdArray::Bool(booleans));
30
31    numrst::io::save_zfile(&ndarrays, tmpfile.path()).unwrap();
32
33    let ndarrays = numrst::io::load_zfile(tmpfile.path()).unwrap();
34    for (name, _) in ndarrays {
35        println!("{}", name);
36    }
37    Ok(())
38}
examples/npy.rs (line 12)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let tmpfile = NamedTempFile::new().unwrap();
8
9    let scalar = NdArray::new(1).unwrap();
10    let vector_f32 = NdArray::new(&[1.0f32, 2., 3.]).unwrap();
11    let matrix_f32 = NdArray::new(&[[1, 2, 3], [3, 4, 5]]).unwrap();
12    let ones_f32 = NdArray::<f32>::ones((2, 9)).unwrap();
13    let randn_f64 = NdArray::randn(0.0f64, 1., (1, 2, 3)).unwrap();
14    let fill_f64 = NdArray::full((2, 3, 4), 1.2).unwrap();
15    let arange_f64 = NdArray::arange(0., 10.).unwrap();
16    let trues = NdArray::trues((3, 4)).unwrap();
17    let booleans = NdArray::new(&[[true, false], [false, true]]).unwrap();
18
19    let mut ndarrays = HashMap::new();
20    ndarrays.insert("scalar".to_string(), DynamicNdArray::I32(scalar));
21    ndarrays.insert("vector_f32".to_string(), DynamicNdArray::F32(vector_f32));
22    ndarrays.insert("matrix_f32".to_string(), DynamicNdArray::I32(matrix_f32));
23    ndarrays.insert("ones_f32".to_string(), DynamicNdArray::F32(ones_f32));
24    ndarrays.insert("randn_f64".to_string(), DynamicNdArray::F64(randn_f64));
25    ndarrays.insert("fill_f64".to_string(), DynamicNdArray::F64(fill_f64));
26    ndarrays.insert("arange_f64".to_string(), DynamicNdArray::F64(arange_f64));
27    ndarrays.insert("trues".to_string(), DynamicNdArray::Bool(trues));
28    ndarrays.insert("booleans".to_string(), DynamicNdArray::Bool(booleans));
29
30    numrst::io::save_npz_file(&ndarrays, tmpfile.path()).unwrap();
31
32    let ndarrays = numrst::io::load_npz_file(tmpfile.path()).unwrap();
33    for (name, _) in ndarrays {
34        println!("{}", name);
35    }
36
37    Ok(())
38}
Source

pub fn ones_like(&self) -> Result<Self>

Creates a one-filled array with the same shape as self.

Source

pub fn arange(start: T, end: T) -> Result<Self>

Creates a 1-D array with values from start up to (but not including) end.

use numrst::NdArray;

let a = NdArray::arange(0., 5.).unwrap();
println!("{}", a);
Examples found in repository?
examples/broadcasting.rs (line 5)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let a = NdArray::<f32>::ones((3, 3))?;
5    let b = NdArray::<f32>::arange(0.0, 3.0)?.reshape((3, 1))?;
6
7    let c = a.broadcast_add(&b)?; // broadcasting
8    println!("a:\n{}", a);
9    println!("b:\n{}", b);
10    println!("a + b (broadcast):\n{}", c);
11
12    Ok(())
13}
More examples
Hide additional examples
examples/indexing.rs (line 4)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let arr = NdArray::<u32>::arange(0, 27)?.reshape((3, 3, 3))?;
5
6    let single = arr.index(1)?; // single element along first axis
7    let slice = arr.index(rng!(1:3))?; // range
8    let mixed = arr.index((rng!(0:2), .., 1..2))?; // mixed slicing
9
10    println!("arr:\n{}", arr);
11    println!("index(1):\n{}", single);
12    println!("index(rng!(1:3)):\n{}", slice);
13    println!("index((rng!(0:2), .., 1..2)):\n{}", mixed);
14
15    Ok(())
16}
examples/construct.rs (line 7)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // Create arrays with different constructors
5    let zeros = NdArray::<f32>::zeros((2, 3))?;
6    let ones = NdArray::<f32>::ones((2, 3))?;
7    let arange = NdArray::<i32>::arange(0, 10)?;
8    let rand = NdArray::<f32>::rand(0.0, 1.0, (2, 5, 3, 4))?;
9    let randn = NdArray::<f32>::randn(0.0, 1.0, (2, 2))?;
10
11    println!("zeros:\n{}", zeros);
12    println!("ones:\n{}", ones);
13    println!("arange:\n{}", arange);
14    println!("rand:\n{}", rand);
15    println!("randn:\n{}", randn);
16
17    Ok(())
18}
examples/reductions.rs (line 4)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let arr = NdArray::<f32>::arange(1.0, 10.0)?.reshape((3, 3))?;
5
6    let sum = arr.sum();
7    let prod = arr.product();
8    let min = arr.min();
9    let max = arr.max();
10    let mean = arr.mean();
11    let var = arr.var();
12    let std = arr.std();
13
14    println!("arr:\n{}", arr);
15    println!("sum = {}", sum);
16    println!("product = {}", prod);
17    println!("min = {}", min);
18    println!("max = {}", max);
19    println!("mean = {:?}", mean);
20    println!("var = {:?}", var);
21    println!("std = {:?}", std);
22
23    Ok(())
24}
examples/logic.rs (line 5)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
examples/nrst.rs (line 15)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let tmpfile = NamedTempFile::new().unwrap();
8
9    let scalar = NdArray::new(1).unwrap();
10    let vector_f32 = NdArray::new(&[1.0f32, 2., 3.]).unwrap();
11    let matrix_f32 = NdArray::new(&[[1, 2, 3], [3, 4, 5]]).unwrap();
12    let ones_f32 = NdArray::<f32>::ones((2, 9)).unwrap();
13    let randn_f64 = NdArray::randn(0.0f64, 1., (1, 2, 3)).unwrap();
14    let fill_f64 = NdArray::full((2, 3, 4), 1.2).unwrap();
15    let arange_f64 = NdArray::arange(0., 10.).unwrap();
16    let trues = NdArray::trues((3, 4)).unwrap();
17    let booleans = NdArray::new(&[[true, false], [false, true]]).unwrap();
18
19
20    let mut ndarrays = HashMap::new();
21    ndarrays.insert("scalar".to_string(), DynamicNdArray::I32(scalar));
22    ndarrays.insert("vector_f32".to_string(), DynamicNdArray::F32(vector_f32));
23    ndarrays.insert("matrix_f32".to_string(), DynamicNdArray::I32(matrix_f32));
24    ndarrays.insert("ones_f32".to_string(), DynamicNdArray::F32(ones_f32));
25    ndarrays.insert("randn_f64".to_string(), DynamicNdArray::F64(randn_f64));
26    ndarrays.insert("fill_f64".to_string(), DynamicNdArray::F64(fill_f64));
27    ndarrays.insert("arange_f64".to_string(), DynamicNdArray::F64(arange_f64));
28    ndarrays.insert("trues".to_string(), DynamicNdArray::Bool(trues));
29    ndarrays.insert("booleans".to_string(), DynamicNdArray::Bool(booleans));
30
31    numrst::io::save_zfile(&ndarrays, tmpfile.path()).unwrap();
32
33    let ndarrays = numrst::io::load_zfile(tmpfile.path()).unwrap();
34    for (name, _) in ndarrays {
35        println!("{}", name);
36    }
37    Ok(())
38}
Source

pub fn from_vec<V: Into<Vec<T>>, S: Into<Shape>>( vec: V, shape: S, ) -> Result<Self>

Creates an array from a flat Vec<T> and explicit shape.

use numrst::NdArray;

let a = NdArray::from_vec(vec![1, 2, 3, 4], (2, 2)).unwrap();
println!("{}", a);
Source

pub fn eye(size: usize) -> Result<Self>

Source

pub fn diag(diag: &[T]) -> Result<Self>

Source§

impl<T: WithDType + SampleUniform> NdArray<T>

Source

pub fn rand<S: Into<Shape>>(min: T, max: T, shape: S) -> Result<Self>

Creates an array with uniformly distributed random values in [min, max).

use numrst::NdArray;

let a = NdArray::<f32>::rand(0., 1., (2, 3)).unwrap();
println!("{}", a);
Examples found in repository?
examples/matmul.rs (line 4)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let m1 = NdArray::<f32>::rand(0.0, 1.0, (2, 3))?;
5    let m2 = NdArray::<f32>::rand(0.0, 1.0, (3, 4))?;
6    let m3 = m1.matmul(&m2)?;
7
8    println!("m1:\n{}", m1);
9    println!("m2:\n{}", m2);
10    println!("m1 @ m2:\n{}", m3);
11
12    Ok(())
13}
More examples
Hide additional examples
examples/construct.rs (line 8)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // Create arrays with different constructors
5    let zeros = NdArray::<f32>::zeros((2, 3))?;
6    let ones = NdArray::<f32>::ones((2, 3))?;
7    let arange = NdArray::<i32>::arange(0, 10)?;
8    let rand = NdArray::<f32>::rand(0.0, 1.0, (2, 5, 3, 4))?;
9    let randn = NdArray::<f32>::randn(0.0, 1.0, (2, 2))?;
10
11    println!("zeros:\n{}", zeros);
12    println!("ones:\n{}", ones);
13    println!("arange:\n{}", arange);
14    println!("rand:\n{}", rand);
15    println!("randn:\n{}", randn);
16
17    Ok(())
18}
Source

pub fn rand_like(&self, min: T, max: T) -> Result<Self>

Creates a random array with the same shape as self.

Source§

impl<F: FloatDType> NdArray<F>

Source

pub fn linspace(start: F, stop: F, num: usize) -> Result<Self>

Generate a 1-D NdArray of num evenly spaced values over the interval [start, stop).

§Example
let arr = NdArray::linspace(0.0, 1.0, 5).unwrap();
assert_eq!(arr.to_vec(), [0.0, 0.2, 0.4, 0.6000000000000001, 0.8]);
Source§

impl<F: FloatDType> NdArray<F>

Source

pub fn randn<S: Into<Shape>>(mean: F, std: F, shape: S) -> Result<Self>

Creates an array with normally distributed random values with given mean and std.

use numrst::NdArray;

let a = NdArray::<f64>::randn(0.0, 1.0, (2, 2)).unwrap();
println!("{}", a);
Examples found in repository?
examples/construct.rs (line 9)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // Create arrays with different constructors
5    let zeros = NdArray::<f32>::zeros((2, 3))?;
6    let ones = NdArray::<f32>::ones((2, 3))?;
7    let arange = NdArray::<i32>::arange(0, 10)?;
8    let rand = NdArray::<f32>::rand(0.0, 1.0, (2, 5, 3, 4))?;
9    let randn = NdArray::<f32>::randn(0.0, 1.0, (2, 2))?;
10
11    println!("zeros:\n{}", zeros);
12    println!("ones:\n{}", ones);
13    println!("arange:\n{}", arange);
14    println!("rand:\n{}", rand);
15    println!("randn:\n{}", randn);
16
17    Ok(())
18}
More examples
Hide additional examples
examples/nrst.rs (line 13)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let tmpfile = NamedTempFile::new().unwrap();
8
9    let scalar = NdArray::new(1).unwrap();
10    let vector_f32 = NdArray::new(&[1.0f32, 2., 3.]).unwrap();
11    let matrix_f32 = NdArray::new(&[[1, 2, 3], [3, 4, 5]]).unwrap();
12    let ones_f32 = NdArray::<f32>::ones((2, 9)).unwrap();
13    let randn_f64 = NdArray::randn(0.0f64, 1., (1, 2, 3)).unwrap();
14    let fill_f64 = NdArray::full((2, 3, 4), 1.2).unwrap();
15    let arange_f64 = NdArray::arange(0., 10.).unwrap();
16    let trues = NdArray::trues((3, 4)).unwrap();
17    let booleans = NdArray::new(&[[true, false], [false, true]]).unwrap();
18
19
20    let mut ndarrays = HashMap::new();
21    ndarrays.insert("scalar".to_string(), DynamicNdArray::I32(scalar));
22    ndarrays.insert("vector_f32".to_string(), DynamicNdArray::F32(vector_f32));
23    ndarrays.insert("matrix_f32".to_string(), DynamicNdArray::I32(matrix_f32));
24    ndarrays.insert("ones_f32".to_string(), DynamicNdArray::F32(ones_f32));
25    ndarrays.insert("randn_f64".to_string(), DynamicNdArray::F64(randn_f64));
26    ndarrays.insert("fill_f64".to_string(), DynamicNdArray::F64(fill_f64));
27    ndarrays.insert("arange_f64".to_string(), DynamicNdArray::F64(arange_f64));
28    ndarrays.insert("trues".to_string(), DynamicNdArray::Bool(trues));
29    ndarrays.insert("booleans".to_string(), DynamicNdArray::Bool(booleans));
30
31    numrst::io::save_zfile(&ndarrays, tmpfile.path()).unwrap();
32
33    let ndarrays = numrst::io::load_zfile(tmpfile.path()).unwrap();
34    for (name, _) in ndarrays {
35        println!("{}", name);
36    }
37    Ok(())
38}
examples/npy.rs (line 13)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let tmpfile = NamedTempFile::new().unwrap();
8
9    let scalar = NdArray::new(1).unwrap();
10    let vector_f32 = NdArray::new(&[1.0f32, 2., 3.]).unwrap();
11    let matrix_f32 = NdArray::new(&[[1, 2, 3], [3, 4, 5]]).unwrap();
12    let ones_f32 = NdArray::<f32>::ones((2, 9)).unwrap();
13    let randn_f64 = NdArray::randn(0.0f64, 1., (1, 2, 3)).unwrap();
14    let fill_f64 = NdArray::full((2, 3, 4), 1.2).unwrap();
15    let arange_f64 = NdArray::arange(0., 10.).unwrap();
16    let trues = NdArray::trues((3, 4)).unwrap();
17    let booleans = NdArray::new(&[[true, false], [false, true]]).unwrap();
18
19    let mut ndarrays = HashMap::new();
20    ndarrays.insert("scalar".to_string(), DynamicNdArray::I32(scalar));
21    ndarrays.insert("vector_f32".to_string(), DynamicNdArray::F32(vector_f32));
22    ndarrays.insert("matrix_f32".to_string(), DynamicNdArray::I32(matrix_f32));
23    ndarrays.insert("ones_f32".to_string(), DynamicNdArray::F32(ones_f32));
24    ndarrays.insert("randn_f64".to_string(), DynamicNdArray::F64(randn_f64));
25    ndarrays.insert("fill_f64".to_string(), DynamicNdArray::F64(fill_f64));
26    ndarrays.insert("arange_f64".to_string(), DynamicNdArray::F64(arange_f64));
27    ndarrays.insert("trues".to_string(), DynamicNdArray::Bool(trues));
28    ndarrays.insert("booleans".to_string(), DynamicNdArray::Bool(booleans));
29
30    numrst::io::save_npz_file(&ndarrays, tmpfile.path()).unwrap();
31
32    let ndarrays = numrst::io::load_npz_file(tmpfile.path()).unwrap();
33    for (name, _) in ndarrays {
34        println!("{}", name);
35    }
36
37    Ok(())
38}
Source

pub fn randn_like(&self, mean: F, std: F) -> Result<Self>

Creates a normal-distributed random array with the same shape as self.

Examples found in repository?
examples/view.rs (line 8)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let total = NdArray::<f32>::zeros((5, 5)).unwrap();
5
6    {
7        let mut sub = total.index((1..3, 2..4)).unwrap();
8        let source = sub.randn_like(0.0, 1.0).unwrap();
9        let mut sub_view = sub.matrix_view_mut().unwrap();
10
11        sub_view.copy_from(&source).unwrap();
12    }
13    
14    println!("{}", total);
15
16    Ok(())
17}
Source§

impl NdArray<bool>

Source

pub fn trues<S: Into<Shape>>(shape: S) -> Result<Self>

Creates a boolean array filled with true.

use numrst::NdArray;

let a = NdArray::trues((2, 2)).unwrap();
println!("{}", a);
Examples found in repository?
examples/logic.rs (line 21)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
More examples
Hide additional examples
examples/nrst.rs (line 16)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let tmpfile = NamedTempFile::new().unwrap();
8
9    let scalar = NdArray::new(1).unwrap();
10    let vector_f32 = NdArray::new(&[1.0f32, 2., 3.]).unwrap();
11    let matrix_f32 = NdArray::new(&[[1, 2, 3], [3, 4, 5]]).unwrap();
12    let ones_f32 = NdArray::<f32>::ones((2, 9)).unwrap();
13    let randn_f64 = NdArray::randn(0.0f64, 1., (1, 2, 3)).unwrap();
14    let fill_f64 = NdArray::full((2, 3, 4), 1.2).unwrap();
15    let arange_f64 = NdArray::arange(0., 10.).unwrap();
16    let trues = NdArray::trues((3, 4)).unwrap();
17    let booleans = NdArray::new(&[[true, false], [false, true]]).unwrap();
18
19
20    let mut ndarrays = HashMap::new();
21    ndarrays.insert("scalar".to_string(), DynamicNdArray::I32(scalar));
22    ndarrays.insert("vector_f32".to_string(), DynamicNdArray::F32(vector_f32));
23    ndarrays.insert("matrix_f32".to_string(), DynamicNdArray::I32(matrix_f32));
24    ndarrays.insert("ones_f32".to_string(), DynamicNdArray::F32(ones_f32));
25    ndarrays.insert("randn_f64".to_string(), DynamicNdArray::F64(randn_f64));
26    ndarrays.insert("fill_f64".to_string(), DynamicNdArray::F64(fill_f64));
27    ndarrays.insert("arange_f64".to_string(), DynamicNdArray::F64(arange_f64));
28    ndarrays.insert("trues".to_string(), DynamicNdArray::Bool(trues));
29    ndarrays.insert("booleans".to_string(), DynamicNdArray::Bool(booleans));
30
31    numrst::io::save_zfile(&ndarrays, tmpfile.path()).unwrap();
32
33    let ndarrays = numrst::io::load_zfile(tmpfile.path()).unwrap();
34    for (name, _) in ndarrays {
35        println!("{}", name);
36    }
37    Ok(())
38}
examples/npy.rs (line 16)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let tmpfile = NamedTempFile::new().unwrap();
8
9    let scalar = NdArray::new(1).unwrap();
10    let vector_f32 = NdArray::new(&[1.0f32, 2., 3.]).unwrap();
11    let matrix_f32 = NdArray::new(&[[1, 2, 3], [3, 4, 5]]).unwrap();
12    let ones_f32 = NdArray::<f32>::ones((2, 9)).unwrap();
13    let randn_f64 = NdArray::randn(0.0f64, 1., (1, 2, 3)).unwrap();
14    let fill_f64 = NdArray::full((2, 3, 4), 1.2).unwrap();
15    let arange_f64 = NdArray::arange(0., 10.).unwrap();
16    let trues = NdArray::trues((3, 4)).unwrap();
17    let booleans = NdArray::new(&[[true, false], [false, true]]).unwrap();
18
19    let mut ndarrays = HashMap::new();
20    ndarrays.insert("scalar".to_string(), DynamicNdArray::I32(scalar));
21    ndarrays.insert("vector_f32".to_string(), DynamicNdArray::F32(vector_f32));
22    ndarrays.insert("matrix_f32".to_string(), DynamicNdArray::I32(matrix_f32));
23    ndarrays.insert("ones_f32".to_string(), DynamicNdArray::F32(ones_f32));
24    ndarrays.insert("randn_f64".to_string(), DynamicNdArray::F64(randn_f64));
25    ndarrays.insert("fill_f64".to_string(), DynamicNdArray::F64(fill_f64));
26    ndarrays.insert("arange_f64".to_string(), DynamicNdArray::F64(arange_f64));
27    ndarrays.insert("trues".to_string(), DynamicNdArray::Bool(trues));
28    ndarrays.insert("booleans".to_string(), DynamicNdArray::Bool(booleans));
29
30    numrst::io::save_npz_file(&ndarrays, tmpfile.path()).unwrap();
31
32    let ndarrays = numrst::io::load_npz_file(tmpfile.path()).unwrap();
33    for (name, _) in ndarrays {
34        println!("{}", name);
35    }
36
37    Ok(())
38}
Source

pub fn falses<S: Into<Shape>>(shape: S) -> Result<Self>

Creates a boolean array filled with false.

Examples found in repository?
examples/logic.rs (line 22)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
Source§

impl<T: WithDType> NdArray<T>

Source

pub fn take<I: UnsignedIntDType>( &self, indices: &NdArray<I>, ) -> Result<NdArray<T>>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn matrix_get(&self, row: usize, col: usize) -> Result<T>

Source

pub fn matrix_set(&self, row: usize, col: usize, val: T) -> Result<()>

Source

pub fn vector_get(&self, n: usize) -> Result<T>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn iter(&self) -> NdArrayIter<'_, T>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn squeeze<D: Dim>(&self, dim: D) -> Result<Self>

Creates a new tensor with the specified dimension removed if its size was one.

use numrst::{NdArray, DType, D};
let a = NdArray::<f32>::zeros((2, 3, 1)).unwrap();

let c = a.squeeze(2).unwrap();
assert_eq!(c.shape().dims(), &[2, 3]);
Examples found in repository?
examples/shape.rs (line 20)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Reshape ---
5    let a = NdArray::<i32>::arange(0, 12)?;
6    let a2d = a.reshape((3, 4))?;
7    let a3d = a.reshape((2, 2, 3))?;
8
9    println!("Original a (1D):\n{}", a);
10    println!("Reshaped a (3x4):\n{}", a2d);
11    println!("Reshaped a (2x2x3):\n{}", a3d);
12
13    // --- Transpose ---
14    let t = a2d.transpose(0, 1)?;
15    println!("Transpose a2d (swap dim 0 <-> 1):\n{}", t);
16
17    // --- Unsqueeze & Squeeze ---
18    let b = NdArray::<f32>::arange(0.0, 6.0)?.reshape((2, 3))?;
19    let b_unsq = b.unsqueeze(0)?; // add axis at front -> (1,2,3)
20    let b_sq = b_unsq.squeeze(0)?; // remove axis -> (2,3)
21
22    println!("b shape: {}", b.shape());
23    println!("b_unsq shape: {}", b_unsq.shape());
24    println!("b_sq shape: {}", b_sq.shape());
25
26    // --- Narrow & Narrow Range ---
27    let narrowed = b.narrow(1, 0, 2)?; // take first 2 cols along axis 1
28    let narrowed_range = b.narrow_range(1, &rng!(0:2))?;
29
30    println!("narrowed (axis=1, first 2 cols):\n{}", narrowed);
31    println!("narrowed_range (axis=1, 0..2):\n{}", narrowed_range);
32
33    // --- Concatenate ---
34    let c1 = NdArray::<i32>::full((2, 2), 1)?;
35    let c2 = NdArray::<i32>::full((2, 2), 2)?;
36    let cat = NdArray::cat(&[&c1, &c2], 0)?; // concat along axis=0
37
38    println!("Concatenate along axis=0:\n{}", cat);
39
40    // --- Stack ---
41    let s1 = NdArray::<i32>::full((2, 2), 3)?;
42    let s2 = NdArray::<i32>::full((2, 2), 4)?;
43    let stacked = NdArray::stack(&[&s1, &s2], 0)?; // stack new axis
44
45    println!("Stacked along new axis=0:\n{}", stacked);
46
47    Ok(())
48}
Source

pub fn unsqueeze<D: Dim>(&self, dim: D) -> Result<Self>

Creates a new tensor with a dimension of size one inserted at the specified position.

use numrst::{NdArray, DType, D};
let a = NdArray::<f32>::zeros((2, 3)).unwrap();

let c = a.unsqueeze(0).unwrap();
assert_eq!(c.shape().dims(), &[1, 2, 3]);

let c = a.unsqueeze(D::Minus1).unwrap();
assert_eq!(c.shape().dims(), &[2, 3, 1]);
Examples found in repository?
examples/shape.rs (line 19)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Reshape ---
5    let a = NdArray::<i32>::arange(0, 12)?;
6    let a2d = a.reshape((3, 4))?;
7    let a3d = a.reshape((2, 2, 3))?;
8
9    println!("Original a (1D):\n{}", a);
10    println!("Reshaped a (3x4):\n{}", a2d);
11    println!("Reshaped a (2x2x3):\n{}", a3d);
12
13    // --- Transpose ---
14    let t = a2d.transpose(0, 1)?;
15    println!("Transpose a2d (swap dim 0 <-> 1):\n{}", t);
16
17    // --- Unsqueeze & Squeeze ---
18    let b = NdArray::<f32>::arange(0.0, 6.0)?.reshape((2, 3))?;
19    let b_unsq = b.unsqueeze(0)?; // add axis at front -> (1,2,3)
20    let b_sq = b_unsq.squeeze(0)?; // remove axis -> (2,3)
21
22    println!("b shape: {}", b.shape());
23    println!("b_unsq shape: {}", b_unsq.shape());
24    println!("b_sq shape: {}", b_sq.shape());
25
26    // --- Narrow & Narrow Range ---
27    let narrowed = b.narrow(1, 0, 2)?; // take first 2 cols along axis 1
28    let narrowed_range = b.narrow_range(1, &rng!(0:2))?;
29
30    println!("narrowed (axis=1, first 2 cols):\n{}", narrowed);
31    println!("narrowed_range (axis=1, 0..2):\n{}", narrowed_range);
32
33    // --- Concatenate ---
34    let c1 = NdArray::<i32>::full((2, 2), 1)?;
35    let c2 = NdArray::<i32>::full((2, 2), 2)?;
36    let cat = NdArray::cat(&[&c1, &c2], 0)?; // concat along axis=0
37
38    println!("Concatenate along axis=0:\n{}", cat);
39
40    // --- Stack ---
41    let s1 = NdArray::<i32>::full((2, 2), 3)?;
42    let s2 = NdArray::<i32>::full((2, 2), 4)?;
43    let stacked = NdArray::stack(&[&s1, &s2], 0)?; // stack new axis
44
45    println!("Stacked along new axis=0:\n{}", stacked);
46
47    Ok(())
48}
Source

pub fn narrow<D: Dim>(&self, dim: D, start: usize, len: usize) -> Result<Self>

Returns a new tensor that is a narrowed version of the input, the dimension dim ranges from start to start + len.

use numrst::NdArray;
let a = NdArray::new(&[
    [0f32, 1., 2.],
    [3.  , 4., 5.],
    [6.  , 7., 8.]
]).unwrap();

let b = a.narrow(0, 1, 2).unwrap();
assert_eq!(b.shape().dims(), &[2, 3]);

let c = a.narrow(1, 1, 1).unwrap();
assert_eq!(c.shape().dims(), &[3, 1]);
Examples found in repository?
examples/shape.rs (line 27)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Reshape ---
5    let a = NdArray::<i32>::arange(0, 12)?;
6    let a2d = a.reshape((3, 4))?;
7    let a3d = a.reshape((2, 2, 3))?;
8
9    println!("Original a (1D):\n{}", a);
10    println!("Reshaped a (3x4):\n{}", a2d);
11    println!("Reshaped a (2x2x3):\n{}", a3d);
12
13    // --- Transpose ---
14    let t = a2d.transpose(0, 1)?;
15    println!("Transpose a2d (swap dim 0 <-> 1):\n{}", t);
16
17    // --- Unsqueeze & Squeeze ---
18    let b = NdArray::<f32>::arange(0.0, 6.0)?.reshape((2, 3))?;
19    let b_unsq = b.unsqueeze(0)?; // add axis at front -> (1,2,3)
20    let b_sq = b_unsq.squeeze(0)?; // remove axis -> (2,3)
21
22    println!("b shape: {}", b.shape());
23    println!("b_unsq shape: {}", b_unsq.shape());
24    println!("b_sq shape: {}", b_sq.shape());
25
26    // --- Narrow & Narrow Range ---
27    let narrowed = b.narrow(1, 0, 2)?; // take first 2 cols along axis 1
28    let narrowed_range = b.narrow_range(1, &rng!(0:2))?;
29
30    println!("narrowed (axis=1, first 2 cols):\n{}", narrowed);
31    println!("narrowed_range (axis=1, 0..2):\n{}", narrowed_range);
32
33    // --- Concatenate ---
34    let c1 = NdArray::<i32>::full((2, 2), 1)?;
35    let c2 = NdArray::<i32>::full((2, 2), 2)?;
36    let cat = NdArray::cat(&[&c1, &c2], 0)?; // concat along axis=0
37
38    println!("Concatenate along axis=0:\n{}", cat);
39
40    // --- Stack ---
41    let s1 = NdArray::<i32>::full((2, 2), 3)?;
42    let s2 = NdArray::<i32>::full((2, 2), 4)?;
43    let stacked = NdArray::stack(&[&s1, &s2], 0)?; // stack new axis
44
45    println!("Stacked along new axis=0:\n{}", stacked);
46
47    Ok(())
48}
Source

pub fn narrow_range<D: Dim>(&self, dim: D, range: &Range) -> Result<Self>

Returns a new tensor that is a narrowed version of the input, the dimension dim ranges from start to start : end : step.

TODO: set range to a trait param

use numrst::{NdArray, DType, rng, Range};
let a = NdArray::<i32>::zeros((5, 5, 5)).unwrap();

let b = a.narrow(0, 1, 2).unwrap();
assert_eq!(b.shape().dims(), &[2, 5, 5]);

let c = a.narrow_range(1, &rng!(::2)).unwrap();
assert_eq!(c.shape().dims(), &[5, 3, 5]);
Examples found in repository?
examples/shape.rs (line 28)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Reshape ---
5    let a = NdArray::<i32>::arange(0, 12)?;
6    let a2d = a.reshape((3, 4))?;
7    let a3d = a.reshape((2, 2, 3))?;
8
9    println!("Original a (1D):\n{}", a);
10    println!("Reshaped a (3x4):\n{}", a2d);
11    println!("Reshaped a (2x2x3):\n{}", a3d);
12
13    // --- Transpose ---
14    let t = a2d.transpose(0, 1)?;
15    println!("Transpose a2d (swap dim 0 <-> 1):\n{}", t);
16
17    // --- Unsqueeze & Squeeze ---
18    let b = NdArray::<f32>::arange(0.0, 6.0)?.reshape((2, 3))?;
19    let b_unsq = b.unsqueeze(0)?; // add axis at front -> (1,2,3)
20    let b_sq = b_unsq.squeeze(0)?; // remove axis -> (2,3)
21
22    println!("b shape: {}", b.shape());
23    println!("b_unsq shape: {}", b_unsq.shape());
24    println!("b_sq shape: {}", b_sq.shape());
25
26    // --- Narrow & Narrow Range ---
27    let narrowed = b.narrow(1, 0, 2)?; // take first 2 cols along axis 1
28    let narrowed_range = b.narrow_range(1, &rng!(0:2))?;
29
30    println!("narrowed (axis=1, first 2 cols):\n{}", narrowed);
31    println!("narrowed_range (axis=1, 0..2):\n{}", narrowed_range);
32
33    // --- Concatenate ---
34    let c1 = NdArray::<i32>::full((2, 2), 1)?;
35    let c2 = NdArray::<i32>::full((2, 2), 2)?;
36    let cat = NdArray::cat(&[&c1, &c2], 0)?; // concat along axis=0
37
38    println!("Concatenate along axis=0:\n{}", cat);
39
40    // --- Stack ---
41    let s1 = NdArray::<i32>::full((2, 2), 3)?;
42    let s2 = NdArray::<i32>::full((2, 2), 4)?;
43    let stacked = NdArray::stack(&[&s1, &s2], 0)?; // stack new axis
44
45    println!("Stacked along new axis=0:\n{}", stacked);
46
47    Ok(())
48}
Source

pub fn reshape<S: Into<Shape>>(&self, shape: S) -> Result<Self>

Reshape returns a tensor with the target shape provided that the number of elements of the original tensor is the same. If the input tensor is contiguous, this is a view on the original data. Otherwise this uses a new storage and copies the data over, the returned tensor is always contiguous.

The shape can be specified using a tuple of usize and at most one () in which case the behavior is the same as when using -1 in PyTorch: this dimension size is adjusted so as to match the number of elements in the tensor.

use numrst::{NdArray, DType, D};
let a = NdArray::<f32>::zeros((2, 3)).unwrap();

let c = a.reshape((1, 6)).unwrap();
assert_eq!(c.shape().dims(), &[1, 6]);
Examples found in repository?
examples/broadcasting.rs (line 5)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let a = NdArray::<f32>::ones((3, 3))?;
5    let b = NdArray::<f32>::arange(0.0, 3.0)?.reshape((3, 1))?;
6
7    let c = a.broadcast_add(&b)?; // broadcasting
8    println!("a:\n{}", a);
9    println!("b:\n{}", b);
10    println!("a + b (broadcast):\n{}", c);
11
12    Ok(())
13}
More examples
Hide additional examples
examples/indexing.rs (line 4)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let arr = NdArray::<u32>::arange(0, 27)?.reshape((3, 3, 3))?;
5
6    let single = arr.index(1)?; // single element along first axis
7    let slice = arr.index(rng!(1:3))?; // range
8    let mixed = arr.index((rng!(0:2), .., 1..2))?; // mixed slicing
9
10    println!("arr:\n{}", arr);
11    println!("index(1):\n{}", single);
12    println!("index(rng!(1:3)):\n{}", slice);
13    println!("index((rng!(0:2), .., 1..2)):\n{}", mixed);
14
15    Ok(())
16}
examples/reductions.rs (line 4)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let arr = NdArray::<f32>::arange(1.0, 10.0)?.reshape((3, 3))?;
5
6    let sum = arr.sum();
7    let prod = arr.product();
8    let min = arr.min();
9    let max = arr.max();
10    let mean = arr.mean();
11    let var = arr.var();
12    let std = arr.std();
13
14    println!("arr:\n{}", arr);
15    println!("sum = {}", sum);
16    println!("product = {}", prod);
17    println!("min = {}", min);
18    println!("max = {}", max);
19    println!("mean = {:?}", mean);
20    println!("var = {:?}", var);
21    println!("std = {:?}", std);
22
23    Ok(())
24}
examples/logic.rs (line 5)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
examples/shape.rs (line 6)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Reshape ---
5    let a = NdArray::<i32>::arange(0, 12)?;
6    let a2d = a.reshape((3, 4))?;
7    let a3d = a.reshape((2, 2, 3))?;
8
9    println!("Original a (1D):\n{}", a);
10    println!("Reshaped a (3x4):\n{}", a2d);
11    println!("Reshaped a (2x2x3):\n{}", a3d);
12
13    // --- Transpose ---
14    let t = a2d.transpose(0, 1)?;
15    println!("Transpose a2d (swap dim 0 <-> 1):\n{}", t);
16
17    // --- Unsqueeze & Squeeze ---
18    let b = NdArray::<f32>::arange(0.0, 6.0)?.reshape((2, 3))?;
19    let b_unsq = b.unsqueeze(0)?; // add axis at front -> (1,2,3)
20    let b_sq = b_unsq.squeeze(0)?; // remove axis -> (2,3)
21
22    println!("b shape: {}", b.shape());
23    println!("b_unsq shape: {}", b_unsq.shape());
24    println!("b_sq shape: {}", b_sq.shape());
25
26    // --- Narrow & Narrow Range ---
27    let narrowed = b.narrow(1, 0, 2)?; // take first 2 cols along axis 1
28    let narrowed_range = b.narrow_range(1, &rng!(0:2))?;
29
30    println!("narrowed (axis=1, first 2 cols):\n{}", narrowed);
31    println!("narrowed_range (axis=1, 0..2):\n{}", narrowed_range);
32
33    // --- Concatenate ---
34    let c1 = NdArray::<i32>::full((2, 2), 1)?;
35    let c2 = NdArray::<i32>::full((2, 2), 2)?;
36    let cat = NdArray::cat(&[&c1, &c2], 0)?; // concat along axis=0
37
38    println!("Concatenate along axis=0:\n{}", cat);
39
40    // --- Stack ---
41    let s1 = NdArray::<i32>::full((2, 2), 3)?;
42    let s2 = NdArray::<i32>::full((2, 2), 4)?;
43    let stacked = NdArray::stack(&[&s1, &s2], 0)?; // stack new axis
44
45    println!("Stacked along new axis=0:\n{}", stacked);
46
47    Ok(())
48}
Source

pub fn transpose<D1: Dim, D2: Dim>(&self, dim1: D1, dim2: D2) -> Result<Self>

Returns a ndarray that is a transposed version of the input, the given dimensions are

Examples found in repository?
examples/shape.rs (line 14)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Reshape ---
5    let a = NdArray::<i32>::arange(0, 12)?;
6    let a2d = a.reshape((3, 4))?;
7    let a3d = a.reshape((2, 2, 3))?;
8
9    println!("Original a (1D):\n{}", a);
10    println!("Reshaped a (3x4):\n{}", a2d);
11    println!("Reshaped a (2x2x3):\n{}", a3d);
12
13    // --- Transpose ---
14    let t = a2d.transpose(0, 1)?;
15    println!("Transpose a2d (swap dim 0 <-> 1):\n{}", t);
16
17    // --- Unsqueeze & Squeeze ---
18    let b = NdArray::<f32>::arange(0.0, 6.0)?.reshape((2, 3))?;
19    let b_unsq = b.unsqueeze(0)?; // add axis at front -> (1,2,3)
20    let b_sq = b_unsq.squeeze(0)?; // remove axis -> (2,3)
21
22    println!("b shape: {}", b.shape());
23    println!("b_unsq shape: {}", b_unsq.shape());
24    println!("b_sq shape: {}", b_sq.shape());
25
26    // --- Narrow & Narrow Range ---
27    let narrowed = b.narrow(1, 0, 2)?; // take first 2 cols along axis 1
28    let narrowed_range = b.narrow_range(1, &rng!(0:2))?;
29
30    println!("narrowed (axis=1, first 2 cols):\n{}", narrowed);
31    println!("narrowed_range (axis=1, 0..2):\n{}", narrowed_range);
32
33    // --- Concatenate ---
34    let c1 = NdArray::<i32>::full((2, 2), 1)?;
35    let c2 = NdArray::<i32>::full((2, 2), 2)?;
36    let cat = NdArray::cat(&[&c1, &c2], 0)?; // concat along axis=0
37
38    println!("Concatenate along axis=0:\n{}", cat);
39
40    // --- Stack ---
41    let s1 = NdArray::<i32>::full((2, 2), 3)?;
42    let s2 = NdArray::<i32>::full((2, 2), 4)?;
43    let stacked = NdArray::stack(&[&s1, &s2], 0)?; // stack new axis
44
45    println!("Stacked along new axis=0:\n{}", stacked);
46
47    Ok(())
48}
Source

pub fn transpose_last(&self) -> Result<Self>

Source

pub fn cat<A: AsRef<NdArray<T>>, D: Dim>(arrs: &[A], dim: D) -> Result<Self>

Concatenates two or more tensors along a particular dimension.

All tensors must of the same rank, and the output will have the same rank

use numrst::NdArray;
let a = NdArray::<f32>::zeros((2, 3)).unwrap();
let b = NdArray::<f32>::zeros((2, 3)).unwrap();

let c = NdArray::cat(&[&a, &b], 0).unwrap();
assert_eq!(c.dims(), &[4, 3]);

let c = NdArray::cat(&[&a, &b], 1).unwrap();
assert_eq!(c.dims(), &[2, 6]);
Examples found in repository?
examples/shape.rs (line 36)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Reshape ---
5    let a = NdArray::<i32>::arange(0, 12)?;
6    let a2d = a.reshape((3, 4))?;
7    let a3d = a.reshape((2, 2, 3))?;
8
9    println!("Original a (1D):\n{}", a);
10    println!("Reshaped a (3x4):\n{}", a2d);
11    println!("Reshaped a (2x2x3):\n{}", a3d);
12
13    // --- Transpose ---
14    let t = a2d.transpose(0, 1)?;
15    println!("Transpose a2d (swap dim 0 <-> 1):\n{}", t);
16
17    // --- Unsqueeze & Squeeze ---
18    let b = NdArray::<f32>::arange(0.0, 6.0)?.reshape((2, 3))?;
19    let b_unsq = b.unsqueeze(0)?; // add axis at front -> (1,2,3)
20    let b_sq = b_unsq.squeeze(0)?; // remove axis -> (2,3)
21
22    println!("b shape: {}", b.shape());
23    println!("b_unsq shape: {}", b_unsq.shape());
24    println!("b_sq shape: {}", b_sq.shape());
25
26    // --- Narrow & Narrow Range ---
27    let narrowed = b.narrow(1, 0, 2)?; // take first 2 cols along axis 1
28    let narrowed_range = b.narrow_range(1, &rng!(0:2))?;
29
30    println!("narrowed (axis=1, first 2 cols):\n{}", narrowed);
31    println!("narrowed_range (axis=1, 0..2):\n{}", narrowed_range);
32
33    // --- Concatenate ---
34    let c1 = NdArray::<i32>::full((2, 2), 1)?;
35    let c2 = NdArray::<i32>::full((2, 2), 2)?;
36    let cat = NdArray::cat(&[&c1, &c2], 0)?; // concat along axis=0
37
38    println!("Concatenate along axis=0:\n{}", cat);
39
40    // --- Stack ---
41    let s1 = NdArray::<i32>::full((2, 2), 3)?;
42    let s2 = NdArray::<i32>::full((2, 2), 4)?;
43    let stacked = NdArray::stack(&[&s1, &s2], 0)?; // stack new axis
44
45    println!("Stacked along new axis=0:\n{}", stacked);
46
47    Ok(())
48}
Source

pub fn stack<A: AsRef<NdArray<T>>, D: Dim>(args: &[A], dim: D) -> Result<Self>

Stacks two or more tensors along a particular dimension.

All tensors must have the same rank, and the output has one additional rank

use numrst::NdArray;
let a = NdArray::<f32>::zeros((2, 3)).unwrap();
let b = NdArray::<f32>::zeros((2, 3)).unwrap();

let c = NdArray::stack(&[&a, &b], 0).unwrap();
assert_eq!(c.dims(), &[2, 2, 3]);

let c = NdArray::stack(&[&a, &b], 2).unwrap();
assert_eq!(c.dims(), &[2, 3, 2]);
Examples found in repository?
examples/shape.rs (line 43)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Reshape ---
5    let a = NdArray::<i32>::arange(0, 12)?;
6    let a2d = a.reshape((3, 4))?;
7    let a3d = a.reshape((2, 2, 3))?;
8
9    println!("Original a (1D):\n{}", a);
10    println!("Reshaped a (3x4):\n{}", a2d);
11    println!("Reshaped a (2x2x3):\n{}", a3d);
12
13    // --- Transpose ---
14    let t = a2d.transpose(0, 1)?;
15    println!("Transpose a2d (swap dim 0 <-> 1):\n{}", t);
16
17    // --- Unsqueeze & Squeeze ---
18    let b = NdArray::<f32>::arange(0.0, 6.0)?.reshape((2, 3))?;
19    let b_unsq = b.unsqueeze(0)?; // add axis at front -> (1,2,3)
20    let b_sq = b_unsq.squeeze(0)?; // remove axis -> (2,3)
21
22    println!("b shape: {}", b.shape());
23    println!("b_unsq shape: {}", b_unsq.shape());
24    println!("b_sq shape: {}", b_sq.shape());
25
26    // --- Narrow & Narrow Range ---
27    let narrowed = b.narrow(1, 0, 2)?; // take first 2 cols along axis 1
28    let narrowed_range = b.narrow_range(1, &rng!(0:2))?;
29
30    println!("narrowed (axis=1, first 2 cols):\n{}", narrowed);
31    println!("narrowed_range (axis=1, 0..2):\n{}", narrowed_range);
32
33    // --- Concatenate ---
34    let c1 = NdArray::<i32>::full((2, 2), 1)?;
35    let c2 = NdArray::<i32>::full((2, 2), 2)?;
36    let cat = NdArray::cat(&[&c1, &c2], 0)?; // concat along axis=0
37
38    println!("Concatenate along axis=0:\n{}", cat);
39
40    // --- Stack ---
41    let s1 = NdArray::<i32>::full((2, 2), 3)?;
42    let s2 = NdArray::<i32>::full((2, 2), 4)?;
43    let stacked = NdArray::stack(&[&s1, &s2], 0)?; // stack new axis
44
45    println!("Stacked along new axis=0:\n{}", stacked);
46
47    Ok(())
48}
Source

pub fn split<D: Dim>(&self, dim: D) -> Result<Vec<Self>>

Splits a tensor along a specified dimension into multiple sub-tensors.

The tensor is split along the given dim into as many sub-tensors as the size of that dimension. Each sub-tensor has the same shape as the original tensor, except the size along dim becomes 1.

use numrst::NdArray;

let a = NdArray::new(&[[1, 2], [3, 4], [5, 6]]).unwrap();

// Split along axis 0 (rows)
let splits = a.split(0).unwrap();
assert_eq!(splits.len(), 3);
assert_eq!(splits[0].to_vec(), [1, 2]);
assert_eq!(splits[1].to_vec(), [3, 4]);
assert_eq!(splits[2].to_vec(), [5, 6]);

// Split along axis 1 (columns)
let splits = a.split(1).unwrap();
assert_eq!(splits.len(), 2);
assert_eq!(splits[0].to_vec(), [1, 3, 5]);
assert_eq!(splits[1].to_vec(), [2, 4, 6]);

// 1D array
let b = NdArray::new(&[10, 20, 30]).unwrap();
let splits = b.split(0).unwrap();
assert_eq!(splits.len(), 3);
assert_eq!(splits[0].to_vec(), [10]);
assert_eq!(splits[1].to_vec(), [20]);
assert_eq!(splits[2].to_vec(), [30]);
Source

pub fn flatten<D1: Dim, D2: Dim>( &self, start_dim: D1, end_dim: D2, ) -> Result<Self>

Flattens the input tensor on the dimension indexes from start_dim to end_dim (both inclusive).

Source

pub fn flatten_to<D: Dim>(&self, end_dim: D) -> Result<Self>

Flattens the input tensor on the dimension indexes from 0 to end_dim (inclusive).

Source

pub fn flatten_from<D: Dim>(&self, start_dim: D) -> Result<Self>

Flattens the input tensor on the dimension indexes from start_dim (inclusive) to the last dimension.

Source

pub fn flatten_all(&self) -> Result<Self>

Flattens the input tensor by reshaping it into a one dimension tensor.

use numrst::NdArray;
let arr = NdArray::new(&[[0f32, 1.], [2., 3.], [4., 5.]]).unwrap();
let arr = arr.flatten_all().unwrap();
assert_eq!(arr.to_vec(), [0., 1., 2., 3., 4., 5.]);
Source

pub fn repeat<S: Into<Shape>>(&self, shape: S) -> Result<Self>

Repeat this tensor along the specified dimensions.

Source

pub fn repeat_dim<D: Dim>(&self, dim: D, times: usize) -> Result<Self>

Repeat this tensor along the specified dimension with specified times

Source§

impl<T: NumDType> NdArray<T>

Source

pub fn add(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>

Examples found in repository?
examples/arithmetic.rs (line 7)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let a = NdArray::<f32>::ones((2, 2))?;
5    let b = NdArray::<f32>::full((2, 2), 2.0)?;
6
7    let c = a.add(&b)?;
8    let d = b.sub(&a)?;
9    let e = b.mul(&c)?;
10    let f = e.div(&d)?;
11
12    println!("a:\n{:?}", a);
13    println!("b:\n{}", b);
14    println!("a + b:\n{}", c);
15    println!("b - a:\n{:?}", d);
16    println!("b * (a + b):\n{}", e);
17    println!("e / d:\n{}", f);
18
19    Ok(())
20}
Source

pub fn mul(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>

Examples found in repository?
examples/arithmetic.rs (line 9)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let a = NdArray::<f32>::ones((2, 2))?;
5    let b = NdArray::<f32>::full((2, 2), 2.0)?;
6
7    let c = a.add(&b)?;
8    let d = b.sub(&a)?;
9    let e = b.mul(&c)?;
10    let f = e.div(&d)?;
11
12    println!("a:\n{:?}", a);
13    println!("b:\n{}", b);
14    println!("a + b:\n{}", c);
15    println!("b - a:\n{:?}", d);
16    println!("b * (a + b):\n{}", e);
17    println!("e / d:\n{}", f);
18
19    Ok(())
20}
Source

pub fn sub(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>

Examples found in repository?
examples/arithmetic.rs (line 8)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let a = NdArray::<f32>::ones((2, 2))?;
5    let b = NdArray::<f32>::full((2, 2), 2.0)?;
6
7    let c = a.add(&b)?;
8    let d = b.sub(&a)?;
9    let e = b.mul(&c)?;
10    let f = e.div(&d)?;
11
12    println!("a:\n{:?}", a);
13    println!("b:\n{}", b);
14    println!("a + b:\n{}", c);
15    println!("b - a:\n{:?}", d);
16    println!("b * (a + b):\n{}", e);
17    println!("e / d:\n{}", f);
18
19    Ok(())
20}
Source

pub fn div(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>

Examples found in repository?
examples/arithmetic.rs (line 10)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let a = NdArray::<f32>::ones((2, 2))?;
5    let b = NdArray::<f32>::full((2, 2), 2.0)?;
6
7    let c = a.add(&b)?;
8    let d = b.sub(&a)?;
9    let e = b.mul(&c)?;
10    let f = e.div(&d)?;
11
12    println!("a:\n{:?}", a);
13    println!("b:\n{}", b);
14    println!("a + b:\n{}", c);
15    println!("b - a:\n{:?}", d);
16    println!("b * (a + b):\n{}", e);
17    println!("e / d:\n{}", f);
18
19    Ok(())
20}
Source

pub fn minimum(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>

Source

pub fn maximum(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>

Source§

impl<T: NumDType> NdArray<T>

Source

pub fn add_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>

Source

pub fn mul_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>

Source

pub fn sub_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>

Source

pub fn div_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>

Source

pub fn minimum_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>

Source

pub fn maximum_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>

Source§

impl<T: NumDType> NdArray<T>

Source

pub fn eq(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>

Examples found in repository?
examples/logic.rs (line 8)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
Source

pub fn ne(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>

Examples found in repository?
examples/logic.rs (line 9)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
Source

pub fn le(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>

Source

pub fn ge(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>

Examples found in repository?
examples/logic.rs (line 11)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
Source

pub fn lt(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>

Examples found in repository?
examples/logic.rs (line 10)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
Source

pub fn gt(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>

Source

pub fn cmp( &self, rhs: impl NdArrayBinaryOpRhs<T>, op: CmpOp, ) -> Result<NdArray<bool>>

Source§

impl NdArray<bool>

Source

pub fn and(&self, rhs: impl NdArrayBinaryOpRhs<bool>) -> Result<NdArray<bool>>

Examples found in repository?
examples/logic.rs (line 24)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
Source

pub fn or(&self, rhs: impl NdArrayBinaryOpRhs<bool>) -> Result<NdArray<bool>>

Examples found in repository?
examples/logic.rs (line 25)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
Source

pub fn xor(&self, rhs: impl NdArrayBinaryOpRhs<bool>) -> Result<NdArray<bool>>

Examples found in repository?
examples/logic.rs (line 26)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
Source

pub fn not(&self) -> NdArray<bool>

Source§

impl<T: NumDType> NdArray<T>

Source

pub fn affine(&self, mul: T, add: T) -> Result<Self>

Source

pub fn affine_assign(&self, mul: T, add: T) -> Result<()>

Source§

impl<F: FloatDType> NdArray<F>

Source

pub fn exp(&self) -> Self

Source

pub fn sin(&self) -> Self

Source

pub fn cos(&self) -> Self

Source

pub fn tanh(&self) -> Self

Source

pub fn sqrt(&self) -> Self

Source

pub fn floor(&self) -> Self

Source

pub fn ceil(&self) -> Self

Source

pub fn round(&self) -> Self

Source

pub fn abs(&self) -> Self

Source

pub fn neg(&self) -> Self

Source

pub fn ln(&self) -> Self

Source

pub fn recip(&self) -> Self

Source

pub fn exp_assign(&self)

Source

pub fn sin_assign(&self)

Source

pub fn cos_assign(&self)

Source

pub fn sqrt_assign(&self)

Source

pub fn tanh_assign(&self)

Source

pub fn floor_assign(&self)

Source

pub fn ceil_assign(&self)

Source

pub fn round_assign(&self)

Source

pub fn abs_assign(&self)

Source

pub fn neg_assign(&self)

Source

pub fn ln_assign(&self)

Source

pub fn recip_assign(&self)

Source§

impl<T: NumDType> NdArray<T>

Source

pub fn matmul(&self, rhs: &Self) -> Result<Self>

Returns the matrix-multiplication of the input tensor with the other provided tensor.

§Arguments
  • self - A tensor with dimensions b1, b2, ..., bi, m, k.
  • rhs - A tensor with dimensions b1, b2, ..., bi, k, n.

The resulting tensor has dimensions b1, b2, ..., bi, m, n.

Examples found in repository?
examples/matmul.rs (line 6)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let m1 = NdArray::<f32>::rand(0.0, 1.0, (2, 3))?;
5    let m2 = NdArray::<f32>::rand(0.0, 1.0, (3, 4))?;
6    let m3 = m1.matmul(&m2)?;
7
8    println!("m1:\n{}", m1);
9    println!("m2:\n{}", m2);
10    println!("m1 @ m2:\n{}", m3);
11
12    Ok(())
13}
Source§

impl<T: NumDType> NdArray<T>

Source

pub fn sum_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceSum as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>

Source

pub fn product_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceProduct as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>

Source

pub fn min_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceMin as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>

Source

pub fn argmin_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceArgMin as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>

Source

pub fn max_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceMax as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>

Source

pub fn argmax_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceArgMax as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>

Source

pub fn mean_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceMean as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>
where ReduceMean: ReduceOpByCategory<T, DimArrayIter<'a, T>>,

Source

pub fn var_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceVar as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>
where ReduceVar: ReduceOpByCategory<T, DimArrayIter<'a, T>>,

Source

pub fn std_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceStd as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>
where ReduceStd: ReduceOpByCategory<T, DimArrayIter<'a, T>>,

Source§

impl<T: NumDType> NdArray<T>

Source

pub fn sum(&self) -> T

Examples found in repository?
examples/reductions.rs (line 6)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let arr = NdArray::<f32>::arange(1.0, 10.0)?.reshape((3, 3))?;
5
6    let sum = arr.sum();
7    let prod = arr.product();
8    let min = arr.min();
9    let max = arr.max();
10    let mean = arr.mean();
11    let var = arr.var();
12    let std = arr.std();
13
14    println!("arr:\n{}", arr);
15    println!("sum = {}", sum);
16    println!("product = {}", prod);
17    println!("min = {}", min);
18    println!("max = {}", max);
19    println!("mean = {:?}", mean);
20    println!("var = {:?}", var);
21    println!("std = {:?}", std);
22
23    Ok(())
24}
Source

pub fn product(&self) -> T

Examples found in repository?
examples/reductions.rs (line 7)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let arr = NdArray::<f32>::arange(1.0, 10.0)?.reshape((3, 3))?;
5
6    let sum = arr.sum();
7    let prod = arr.product();
8    let min = arr.min();
9    let max = arr.max();
10    let mean = arr.mean();
11    let var = arr.var();
12    let std = arr.std();
13
14    println!("arr:\n{}", arr);
15    println!("sum = {}", sum);
16    println!("product = {}", prod);
17    println!("min = {}", min);
18    println!("max = {}", max);
19    println!("mean = {:?}", mean);
20    println!("var = {:?}", var);
21    println!("std = {:?}", std);
22
23    Ok(())
24}
Source

pub fn min(&self) -> T

Examples found in repository?
examples/reductions.rs (line 8)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let arr = NdArray::<f32>::arange(1.0, 10.0)?.reshape((3, 3))?;
5
6    let sum = arr.sum();
7    let prod = arr.product();
8    let min = arr.min();
9    let max = arr.max();
10    let mean = arr.mean();
11    let var = arr.var();
12    let std = arr.std();
13
14    println!("arr:\n{}", arr);
15    println!("sum = {}", sum);
16    println!("product = {}", prod);
17    println!("min = {}", min);
18    println!("max = {}", max);
19    println!("mean = {:?}", mean);
20    println!("var = {:?}", var);
21    println!("std = {:?}", std);
22
23    Ok(())
24}
Source

pub fn max(&self) -> T

Examples found in repository?
examples/reductions.rs (line 9)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let arr = NdArray::<f32>::arange(1.0, 10.0)?.reshape((3, 3))?;
5
6    let sum = arr.sum();
7    let prod = arr.product();
8    let min = arr.min();
9    let max = arr.max();
10    let mean = arr.mean();
11    let var = arr.var();
12    let std = arr.std();
13
14    println!("arr:\n{}", arr);
15    println!("sum = {}", sum);
16    println!("product = {}", prod);
17    println!("min = {}", min);
18    println!("max = {}", max);
19    println!("mean = {:?}", mean);
20    println!("var = {:?}", var);
21    println!("std = {:?}", std);
22
23    Ok(())
24}
Source

pub fn mean<'a>( &'a self, ) -> <ReduceMean as ReduceOp<T, NdArrayIter<'a, T>>>::Output
where ReduceMean: ReduceOpByCategory<T, NdArrayIter<'a, T>>,

Examples found in repository?
examples/reductions.rs (line 10)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let arr = NdArray::<f32>::arange(1.0, 10.0)?.reshape((3, 3))?;
5
6    let sum = arr.sum();
7    let prod = arr.product();
8    let min = arr.min();
9    let max = arr.max();
10    let mean = arr.mean();
11    let var = arr.var();
12    let std = arr.std();
13
14    println!("arr:\n{}", arr);
15    println!("sum = {}", sum);
16    println!("product = {}", prod);
17    println!("min = {}", min);
18    println!("max = {}", max);
19    println!("mean = {:?}", mean);
20    println!("var = {:?}", var);
21    println!("std = {:?}", std);
22
23    Ok(())
24}
Source

pub fn var<'a>( &'a self, ) -> <ReduceVar as ReduceOp<T, NdArrayIter<'a, T>>>::Output
where ReduceVar: ReduceOpByCategory<T, NdArrayIter<'a, T>>,

Examples found in repository?
examples/reductions.rs (line 11)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let arr = NdArray::<f32>::arange(1.0, 10.0)?.reshape((3, 3))?;
5
6    let sum = arr.sum();
7    let prod = arr.product();
8    let min = arr.min();
9    let max = arr.max();
10    let mean = arr.mean();
11    let var = arr.var();
12    let std = arr.std();
13
14    println!("arr:\n{}", arr);
15    println!("sum = {}", sum);
16    println!("product = {}", prod);
17    println!("min = {}", min);
18    println!("max = {}", max);
19    println!("mean = {:?}", mean);
20    println!("var = {:?}", var);
21    println!("std = {:?}", std);
22
23    Ok(())
24}
Source

pub fn std<'a>( &'a self, ) -> <ReduceStd as ReduceOp<T, NdArrayIter<'a, T>>>::Output
where ReduceStd: ReduceOpByCategory<T, NdArrayIter<'a, T>>,

Examples found in repository?
examples/reductions.rs (line 12)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let arr = NdArray::<f32>::arange(1.0, 10.0)?.reshape((3, 3))?;
5
6    let sum = arr.sum();
7    let prod = arr.product();
8    let min = arr.min();
9    let max = arr.max();
10    let mean = arr.mean();
11    let var = arr.var();
12    let std = arr.std();
13
14    println!("arr:\n{}", arr);
15    println!("sum = {}", sum);
16    println!("product = {}", prod);
17    println!("min = {}", min);
18    println!("max = {}", max);
19    println!("mean = {:?}", mean);
20    println!("var = {:?}", var);
21    println!("std = {:?}", std);
22
23    Ok(())
24}
Source§

impl NdArray<bool>

Source

pub fn all(&self) -> bool

Source

pub fn any(&self) -> bool

Source

pub fn all_axis<D: Dim>(&self, axis: D) -> Result<NdArray<bool>>

Source

pub fn any_axis<D: Dim>(&self, axis: D) -> Result<NdArray<bool>>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn broadcast_as<S: Into<Shape>>(&self, shape: S) -> Result<Self>

Broadcast the input tensor to the target shape. This returns an error if the input shape is not compatible with the target shape.

If the input shape is i_1, i_2, ... i_k, the target shape has to have k dimensions or more and shape j_1, ..., j_l, t_1, t_2, ..., t_k. The dimensions j_1 to j_l can have any value, the dimension t_a must be equal to i_a if i_a is different from 1. If i_a is equal to 1, any value can be used.

Source§

impl<T: NumDType> NdArray<T>

Source

pub fn broadcast_add(&self, rhs: &Self) -> Result<Self>

Examples found in repository?
examples/broadcasting.rs (line 7)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let a = NdArray::<f32>::ones((3, 3))?;
5    let b = NdArray::<f32>::arange(0.0, 3.0)?.reshape((3, 1))?;
6
7    let c = a.broadcast_add(&b)?; // broadcasting
8    println!("a:\n{}", a);
9    println!("b:\n{}", b);
10    println!("a + b (broadcast):\n{}", c);
11
12    Ok(())
13}
Source

pub fn broadcast_mul(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_sub(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_div(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_maximum(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_minimum(&self, rhs: &Self) -> Result<Self>

Source

pub fn broadcast_eq(&self, rhs: &Self) -> Result<NdArray<bool>>

Source

pub fn broadcast_ne(&self, rhs: &Self) -> Result<NdArray<bool>>

Source

pub fn broadcast_lt(&self, rhs: &Self) -> Result<NdArray<bool>>

Source

pub fn broadcast_le(&self, rhs: &Self) -> Result<NdArray<bool>>

Source

pub fn broadcast_gt(&self, rhs: &Self) -> Result<NdArray<bool>>

Source

pub fn broadcast_ge(&self, rhs: &Self) -> Result<NdArray<bool>>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn copy(&self) -> Self

Source

pub fn copy_from(&self, source: &Self) -> Result<()>

Source

pub fn assign<A: AssignToNdArray<T>>(&self, source: A) -> Result<()>

Source§

impl<From: WithDType> NdArray<From>

Source

pub fn to_dtype<To: WithDType>(&self) -> NdArray<To>
where From: DTypeConvert<To>,

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn filter(&self, conditions: &NdArray<bool>) -> Result<NdArray<T>>

Source

pub fn select<TV, FV>( mask: &NdArray<bool>, true_val: TV, false_val: FV, ) -> Result<Self>
where TV: ConditionValue<T>, FV: ConditionValue<T>,

Examples found in repository?
examples/logic.rs (line 36)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Comparison ops ---
5    let a = NdArray::<i32>::arange(0, 9)?.reshape((3, 3))?;
6    let b = NdArray::<i32>::full((3, 3), 4)?;
7
8    let eq = a.eq(&b)?;
9    let ne = a.ne(&b)?;
10    let lt = a.lt(&b)?;
11    let ge = a.ge(&b)?;
12
13    println!("a:\n{}", a);
14    println!("b:\n{}", b);
15    println!("a == b:\n{}", eq);
16    println!("a != b:\n{}", ne);
17    println!("a < b:\n{}", lt);
18    println!("a >= b:\n{}", ge);
19
20    // --- Boolean logic ops ---
21    let x = NdArray::<bool>::trues((2, 2))?;
22    let y = NdArray::<bool>::falses((2, 2))?;
23
24    let and = x.and(&y)?;
25    let or = x.or(&y)?;
26    let xor = x.xor(&y)?;
27
28    println!("\nx:\n{}", x);
29    println!("y:\n{}", y);
30    println!("x AND y:\n{}", and);
31    println!("x OR y:\n{}", or);
32    println!("x XOR y:\n{}", xor);
33
34    // --- Using select (if-else like) ---
35    let cond = a.lt(&b)?;
36    let chosen = NdArray::<i32>::select(&cond, &a, &b)?;
37
38    println!("\nCondition (a < b):\n{}", cond);
39    println!("Select result (if a<b then a else b):\n{}", chosen);
40
41    Ok(())
42}
Source§

impl<T: WithDType> NdArray<T>

Source

pub fn is_scalar(&self) -> bool

Source

pub fn check_scalar(&self) -> Result<()>

Source

pub fn to_scalar(&self) -> Result<T>

Source

pub fn set_scalar(&self, val: T) -> Result<()>

Source

pub fn storage_ref<'a>(&'a self, start_offset: usize) -> StorageRef<'a, T>

Source

pub fn storage_mut<'a>(&'a self, start_offset: usize) -> StorageMut<'a, T>

Source

pub fn storage_ptr(&self, start_offset: usize) -> *mut T

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn id(&self) -> usize

Source

pub fn shape(&self) -> &Shape

Examples found in repository?
examples/shape.rs (line 22)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    // --- Reshape ---
5    let a = NdArray::<i32>::arange(0, 12)?;
6    let a2d = a.reshape((3, 4))?;
7    let a3d = a.reshape((2, 2, 3))?;
8
9    println!("Original a (1D):\n{}", a);
10    println!("Reshaped a (3x4):\n{}", a2d);
11    println!("Reshaped a (2x2x3):\n{}", a3d);
12
13    // --- Transpose ---
14    let t = a2d.transpose(0, 1)?;
15    println!("Transpose a2d (swap dim 0 <-> 1):\n{}", t);
16
17    // --- Unsqueeze & Squeeze ---
18    let b = NdArray::<f32>::arange(0.0, 6.0)?.reshape((2, 3))?;
19    let b_unsq = b.unsqueeze(0)?; // add axis at front -> (1,2,3)
20    let b_sq = b_unsq.squeeze(0)?; // remove axis -> (2,3)
21
22    println!("b shape: {}", b.shape());
23    println!("b_unsq shape: {}", b_unsq.shape());
24    println!("b_sq shape: {}", b_sq.shape());
25
26    // --- Narrow & Narrow Range ---
27    let narrowed = b.narrow(1, 0, 2)?; // take first 2 cols along axis 1
28    let narrowed_range = b.narrow_range(1, &rng!(0:2))?;
29
30    println!("narrowed (axis=1, first 2 cols):\n{}", narrowed);
31    println!("narrowed_range (axis=1, 0..2):\n{}", narrowed_range);
32
33    // --- Concatenate ---
34    let c1 = NdArray::<i32>::full((2, 2), 1)?;
35    let c2 = NdArray::<i32>::full((2, 2), 2)?;
36    let cat = NdArray::cat(&[&c1, &c2], 0)?; // concat along axis=0
37
38    println!("Concatenate along axis=0:\n{}", cat);
39
40    // --- Stack ---
41    let s1 = NdArray::<i32>::full((2, 2), 3)?;
42    let s2 = NdArray::<i32>::full((2, 2), 4)?;
43    let stacked = NdArray::stack(&[&s1, &s2], 0)?; // stack new axis
44
45    println!("Stacked along new axis=0:\n{}", stacked);
46
47    Ok(())
48}
Source

pub fn dtype(&self) -> DType

Source

pub fn layout(&self) -> &Layout

Source

pub fn dims(&self) -> &[usize]

Source

pub fn dim<D: Dim>(&self, dim: D) -> Result<usize>

Source

pub fn storage(&self) -> RwLockReadGuard<'_, Storage<T>>

Source

pub fn element_count(&self) -> usize

Source

pub fn is_contiguous(&self) -> bool

Source

pub fn rank(&self) -> usize

Source

pub fn to_vec(&self) -> Vec<T>

Source

pub fn storage_indices(&self) -> StorageIndices<'_>

Returns an iterator over storage indices.

This iterator yields the linear (flat) indices as they are laid out in the underlying storage buffer. The order depends on the memory layout (e.g., row-major / column-major / with strides).

Example for shape = (2, 2) in row-major layout: yields: 0, 1, 2, 3

Source

pub fn dim_coordinates(&self) -> DimCoordinates

Returns an iterator over dimension coordinates.

This iterator yields the multi-dimensional coordinates (e.g., [i, j, k, ...]) of each element in the array, independent of the physical storage layout.

Example for shape = (2, 2): yields: [0, 0], [0, 1], [1, 0], [1, 1]

Source

pub fn dims_coordinates<const N: usize>(&self) -> Result<DimNCoordinates<N>>

Source

pub fn dim2_coordinates(&self) -> Result<DimNCoordinates<2>>

Source

pub fn dim3_coordinates(&self) -> Result<DimNCoordinates<3>>

Source

pub fn dim4_coordinates(&self) -> Result<DimNCoordinates<4>>

Source

pub fn dim5_coordinates(&self) -> Result<DimNCoordinates<5>>

Source§

impl<T: WithDType> NdArray<T>

Source

pub fn matrix_view_unsafe(&self) -> Result<MatrixViewUsf<'_, T>>

Source

pub fn vector_view_unsafe(&self) -> Result<VectorViewUsf<'_, T>>

Source

pub fn matrix_view<'a>(&'a self) -> Result<MatrixView<'a, T>>

Source

pub fn matrix_view_mut<'a>(&'a mut self) -> Result<MatrixViewMut<'a, T>>

Examples found in repository?
examples/view.rs (line 9)
3fn main() -> Result<(), Box<dyn std::error::Error>> {
4    let total = NdArray::<f32>::zeros((5, 5)).unwrap();
5
6    {
7        let mut sub = total.index((1..3, 2..4)).unwrap();
8        let source = sub.randn_like(0.0, 1.0).unwrap();
9        let mut sub_view = sub.matrix_view_mut().unwrap();
10
11        sub_view.copy_from(&source).unwrap();
12    }
13    
14    println!("{}", total);
15
16    Ok(())
17}
Source

pub fn vector_view<'a>(&'a self) -> Result<VectorView<'a, T>>

Source

pub fn vector_view_mut<'a>(&'a mut self) -> Result<VectorViewMut<'a, T>>

Source§

impl<T: NumDType> NdArray<T>

Source

pub fn allclose(&self, other: &Self, rtol: f64, atol: f64) -> bool

Source§

impl<D: WithDType + NoUninit> NdArray<D>

Source

pub fn save_npy_writer<W: Write>(&self, writer: &mut W) -> Result<()>

Source

pub fn save_npy_file<P: AsRef<Path>>(&self, path: P) -> Result<()>

Source§

impl<T: WithDType + NoUninit> NdArray<T>

Source

pub fn save_file<P: AsRef<Path>>(&self, path: P) -> Result<()>

Source

pub fn save_writer<W: Write>(&self, writer: &mut W) -> Result<()>

Trait Implementations§

Source§

impl<T: NumDType, R: NdArrayBinaryOpRhs<T>> Add<R> for &NdArray<T>

Source§

type Output = Result<NdArray<T>, Error>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: R) -> Self::Output

Performs the + operation. Read more
Source§

impl<T: NumDType, R: NdArrayBinaryOpRhs<T>> Add<R> for NdArray<T>

Source§

type Output = Result<NdArray<T>, Error>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: R) -> Self::Output

Performs the + operation. Read more
Source§

impl<T: WithDType> AsRef<NdArray<T>> for NdArray<T>

Source§

fn as_ref(&self) -> &NdArray<T>

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<D: Clone> Clone for NdArray<D>

Source§

fn clone(&self) -> NdArray<D>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: WithDType> Debug for NdArray<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: WithDType> Display for NdArray<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: NumDType, R: NdArrayBinaryOpRhs<T>> Div<R> for &NdArray<T>

Source§

type Output = Result<NdArray<T>, Error>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: R) -> Self::Output

Performs the / operation. Read more
Source§

impl<T: NumDType, R: NdArrayBinaryOpRhs<T>> Div<R> for NdArray<T>

Source§

type Output = Result<NdArray<T>, Error>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: R) -> Self::Output

Performs the / operation. Read more
Source§

impl<I: Into<Indexer>, D: WithDType> IndexOp<(I,), D> for NdArray<D>

Source§

fn index(&self, (index): (I,)) -> Result<NdArray<D>>

Source§

impl<I1, I2, D: WithDType> IndexOp<(I1, I2), D> for NdArray<D>
where I1: Into<Indexer>, I2: Into<Indexer>,

Source§

fn index(&self, (I1, I2): (I1, I2)) -> Result<NdArray<D>>

Source§

impl<I1, I2, I3, D: WithDType> IndexOp<(I1, I2, I3), D> for NdArray<D>
where I1: Into<Indexer>, I2: Into<Indexer>, I3: Into<Indexer>,

Source§

fn index(&self, (I1, I2, I3): (I1, I2, I3)) -> Result<NdArray<D>>

Source§

impl<I1, I2, I3, I4, D: WithDType> IndexOp<(I1, I2, I3, I4), D> for NdArray<D>
where I1: Into<Indexer>, I2: Into<Indexer>, I3: Into<Indexer>, I4: Into<Indexer>,

Source§

fn index(&self, (I1, I2, I3, I4): (I1, I2, I3, I4)) -> Result<NdArray<D>>

Source§

impl<I1, I2, I3, I4, I5, D: WithDType> IndexOp<(I1, I2, I3, I4, I5), D> for NdArray<D>
where I1: Into<Indexer>, I2: Into<Indexer>, I3: Into<Indexer>, I4: Into<Indexer>, I5: Into<Indexer>,

Source§

fn index( &self, (I1, I2, I3, I4, I5): (I1, I2, I3, I4, I5), ) -> Result<NdArray<D>>

Source§

impl<I: Into<Indexer>, D: WithDType> IndexOp<I, D> for NdArray<D>

Source§

fn index(&self, index: I) -> Result<NdArray<D>>

Source§

impl<T: NumDType, R: NdArrayBinaryOpRhs<T>> Mul<R> for &NdArray<T>

Source§

type Output = Result<NdArray<T>, Error>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: R) -> Self::Output

Performs the * operation. Read more
Source§

impl<T: NumDType, R: NdArrayBinaryOpRhs<T>> Mul<R> for NdArray<T>

Source§

type Output = Result<NdArray<T>, Error>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: R) -> Self::Output

Performs the * operation. Read more
Source§

impl<T: NumDType, R: NdArrayBinaryOpRhs<T>> Sub<R> for &NdArray<T>

Source§

type Output = Result<NdArray<T>, Error>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: R) -> Self::Output

Performs the - operation. Read more
Source§

impl<T: NumDType, R: NdArrayBinaryOpRhs<T>> Sub<R> for NdArray<T>

Source§

type Output = Result<NdArray<T>, Error>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: R) -> Self::Output

Performs the - operation. Read more

Auto Trait Implementations§

§

impl<D> Freeze for NdArray<D>

§

impl<D> RefUnwindSafe for NdArray<D>

§

impl<D> Send for NdArray<D>
where D: Send + Sync,

§

impl<D> Sync for NdArray<D>
where D: Send + Sync,

§

impl<D> Unpin for NdArray<D>

§

impl<D> UnwindSafe for NdArray<D>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V