pub struct NdArray<D>(/* private fields */);Implementations§
Source§impl<T: WithDType> NdArray<T>
impl<T: WithDType> NdArray<T>
Sourcepub fn new<A: ToNdArray<T>>(array: A) -> Result<Self>
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?
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
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}Sourcepub fn full<S: Into<Shape>>(shape: S, value: T) -> Result<Self>
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?
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
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}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}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}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>
impl<T: NumDType> NdArray<T>
Sourcepub fn zeros<S: Into<Shape>>(shape: S) -> Result<Self>
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?
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
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}Sourcepub fn zero_like(&self) -> Result<Self>
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);Sourcepub fn ones<S: Into<Shape>>(shape: S) -> Result<Self>
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?
More examples
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}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}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}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}Sourcepub fn ones_like(&self) -> Result<Self>
pub fn ones_like(&self) -> Result<Self>
Creates a one-filled array with the same shape as self.
Sourcepub fn arange(start: T, end: T) -> Result<Self>
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?
More examples
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}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}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}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}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}Sourcepub fn from_vec<V: Into<Vec<T>>, S: Into<Shape>>(
vec: V,
shape: S,
) -> Result<Self>
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);pub fn eye(size: usize) -> Result<Self>
pub fn diag(diag: &[T]) -> Result<Self>
Source§impl<T: WithDType + SampleUniform> NdArray<T>where
StandardUniform: Distribution<T>,
impl<T: WithDType + SampleUniform> NdArray<T>where
StandardUniform: Distribution<T>,
Sourcepub fn rand<S: Into<Shape>>(min: T, max: T, shape: S) -> Result<Self>
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?
More examples
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§impl<F: FloatDType> NdArray<F>
impl<F: FloatDType> NdArray<F>
Source§impl<F: FloatDType> NdArray<F>where
StandardNormal: Distribution<F>,
impl<F: FloatDType> NdArray<F>where
StandardNormal: Distribution<F>,
Sourcepub fn randn<S: Into<Shape>>(mean: F, std: F, shape: S) -> Result<Self>
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?
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
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}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}Sourcepub fn randn_like(&self, mean: F, std: F) -> Result<Self>
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?
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>
impl NdArray<bool>
Sourcepub fn trues<S: Into<Shape>>(shape: S) -> Result<Self>
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?
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
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}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}Sourcepub fn falses<S: Into<Shape>>(shape: S) -> Result<Self>
pub fn falses<S: Into<Shape>>(shape: S) -> Result<Self>
Creates a boolean array filled with false.
Examples found in repository?
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>
impl<T: WithDType> NdArray<T>
pub fn matrix_get(&self, row: usize, col: usize) -> Result<T>
pub fn matrix_set(&self, row: usize, col: usize, val: T) -> Result<()>
pub fn vector_get(&self, n: usize) -> Result<T>
Source§impl<T: WithDType> NdArray<T>
impl<T: WithDType> NdArray<T>
Sourcepub fn squeeze<D: Dim>(&self, dim: D) -> Result<Self>
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?
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}Sourcepub fn unsqueeze<D: Dim>(&self, dim: D) -> Result<Self>
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?
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}Sourcepub fn narrow<D: Dim>(&self, dim: D, start: usize, len: usize) -> Result<Self>
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?
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}Sourcepub fn narrow_range<D: Dim>(&self, dim: D, range: &Range) -> Result<Self>
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?
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}Sourcepub fn reshape<S: Into<Shape>>(&self, shape: S) -> Result<Self>
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?
More examples
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}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}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}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}Sourcepub fn transpose<D1: Dim, D2: Dim>(&self, dim1: D1, dim2: D2) -> Result<Self>
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?
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}pub fn transpose_last(&self) -> Result<Self>
Sourcepub fn cat<A: AsRef<NdArray<T>>, D: Dim>(arrs: &[A], dim: D) -> Result<Self>
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?
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}Sourcepub fn stack<A: AsRef<NdArray<T>>, D: Dim>(args: &[A], dim: D) -> Result<Self>
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?
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}Sourcepub fn split<D: Dim>(&self, dim: D) -> Result<Vec<Self>>
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]);Sourcepub fn flatten<D1: Dim, D2: Dim>(
&self,
start_dim: D1,
end_dim: D2,
) -> Result<Self>
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).
Sourcepub fn flatten_to<D: Dim>(&self, end_dim: D) -> Result<Self>
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).
Sourcepub fn flatten_from<D: Dim>(&self, start_dim: D) -> Result<Self>
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.
Sourcepub fn flatten_all(&self) -> Result<Self>
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.]);Sourcepub fn repeat<S: Into<Shape>>(&self, shape: S) -> Result<Self>
pub fn repeat<S: Into<Shape>>(&self, shape: S) -> Result<Self>
Repeat this tensor along the specified dimensions.
Sourcepub fn repeat_dim<D: Dim>(&self, dim: D, times: usize) -> Result<Self>
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>
impl<T: NumDType> NdArray<T>
Sourcepub fn add(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>
pub fn add(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>
Examples found in repository?
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}Sourcepub fn mul(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>
pub fn mul(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>
Examples found in repository?
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}Sourcepub fn sub(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>
pub fn sub(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>
Examples found in repository?
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}Sourcepub fn div(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>
pub fn div(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>
Examples found in repository?
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}pub fn minimum(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>
pub fn maximum(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<Self>
Source§impl<T: NumDType> NdArray<T>
impl<T: NumDType> NdArray<T>
pub fn add_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>
pub fn mul_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>
pub fn sub_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>
pub fn div_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>
pub fn minimum_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>
pub fn maximum_assign(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<()>
Source§impl<T: NumDType> NdArray<T>
impl<T: NumDType> NdArray<T>
Sourcepub fn eq(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>
pub fn eq(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>
Examples found in repository?
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}Sourcepub fn ne(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>
pub fn ne(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>
Examples found in repository?
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}pub fn le(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>
Sourcepub fn ge(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>
pub fn ge(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>
Examples found in repository?
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}Sourcepub fn lt(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>
pub fn lt(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>
Examples found in repository?
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}pub fn gt(&self, rhs: impl NdArrayBinaryOpRhs<T>) -> Result<NdArray<bool>>
pub fn cmp( &self, rhs: impl NdArrayBinaryOpRhs<T>, op: CmpOp, ) -> Result<NdArray<bool>>
Source§impl NdArray<bool>
impl NdArray<bool>
Sourcepub fn and(&self, rhs: impl NdArrayBinaryOpRhs<bool>) -> Result<NdArray<bool>>
pub fn and(&self, rhs: impl NdArrayBinaryOpRhs<bool>) -> Result<NdArray<bool>>
Examples found in repository?
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}Sourcepub fn or(&self, rhs: impl NdArrayBinaryOpRhs<bool>) -> Result<NdArray<bool>>
pub fn or(&self, rhs: impl NdArrayBinaryOpRhs<bool>) -> Result<NdArray<bool>>
Examples found in repository?
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}Sourcepub fn xor(&self, rhs: impl NdArrayBinaryOpRhs<bool>) -> Result<NdArray<bool>>
pub fn xor(&self, rhs: impl NdArrayBinaryOpRhs<bool>) -> Result<NdArray<bool>>
Examples found in repository?
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}pub fn not(&self) -> NdArray<bool>
Source§impl<F: FloatDType> NdArray<F>
impl<F: FloatDType> NdArray<F>
pub fn exp(&self) -> Self
pub fn sin(&self) -> Self
pub fn cos(&self) -> Self
pub fn tanh(&self) -> Self
pub fn sqrt(&self) -> Self
pub fn floor(&self) -> Self
pub fn ceil(&self) -> Self
pub fn round(&self) -> Self
pub fn abs(&self) -> Self
pub fn neg(&self) -> Self
pub fn ln(&self) -> Self
pub fn recip(&self) -> Self
pub fn exp_assign(&self)
pub fn sin_assign(&self)
pub fn cos_assign(&self)
pub fn sqrt_assign(&self)
pub fn tanh_assign(&self)
pub fn floor_assign(&self)
pub fn ceil_assign(&self)
pub fn round_assign(&self)
pub fn abs_assign(&self)
pub fn neg_assign(&self)
pub fn ln_assign(&self)
pub fn recip_assign(&self)
Source§impl<T: NumDType> NdArray<T>
impl<T: NumDType> NdArray<T>
Sourcepub fn matmul(&self, rhs: &Self) -> Result<Self>
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 dimensionsb1, b2, ..., bi, m, k.rhs- A tensor with dimensionsb1, b2, ..., bi, k, n.
The resulting tensor has dimensions b1, b2, ..., bi, m, n.
Source§impl<T: NumDType> NdArray<T>
impl<T: NumDType> NdArray<T>
pub fn sum_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceSum as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>
pub fn product_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceProduct as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>
pub fn min_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceMin as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>
pub fn argmin_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceArgMin as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>
pub fn max_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceMax as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>
pub fn argmax_axis<'a, D: Dim>( &'a self, axis: D, ) -> Result<NdArray<<ReduceArgMax as ReduceOp<T, DimArrayIter<'a, T>>>::Output>>
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>>,
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>>,
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>
impl<T: NumDType> NdArray<T>
Sourcepub fn sum(&self) -> T
pub fn sum(&self) -> T
Examples found in repository?
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}Sourcepub fn product(&self) -> T
pub fn product(&self) -> T
Examples found in repository?
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}Sourcepub fn min(&self) -> T
pub fn min(&self) -> T
Examples found in repository?
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}Sourcepub fn max(&self) -> T
pub fn max(&self) -> T
Examples found in repository?
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}Sourcepub fn mean<'a>(
&'a self,
) -> <ReduceMean as ReduceOp<T, NdArrayIter<'a, T>>>::Outputwhere
ReduceMean: ReduceOpByCategory<T, NdArrayIter<'a, T>>,
pub fn mean<'a>(
&'a self,
) -> <ReduceMean as ReduceOp<T, NdArrayIter<'a, T>>>::Outputwhere
ReduceMean: ReduceOpByCategory<T, NdArrayIter<'a, T>>,
Examples found in repository?
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}Sourcepub fn var<'a>(
&'a self,
) -> <ReduceVar as ReduceOp<T, NdArrayIter<'a, T>>>::Outputwhere
ReduceVar: ReduceOpByCategory<T, NdArrayIter<'a, T>>,
pub fn var<'a>(
&'a self,
) -> <ReduceVar as ReduceOp<T, NdArrayIter<'a, T>>>::Outputwhere
ReduceVar: ReduceOpByCategory<T, NdArrayIter<'a, T>>,
Examples found in repository?
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}Sourcepub fn std<'a>(
&'a self,
) -> <ReduceStd as ReduceOp<T, NdArrayIter<'a, T>>>::Outputwhere
ReduceStd: ReduceOpByCategory<T, NdArrayIter<'a, T>>,
pub fn std<'a>(
&'a self,
) -> <ReduceStd as ReduceOp<T, NdArrayIter<'a, T>>>::Outputwhere
ReduceStd: ReduceOpByCategory<T, NdArrayIter<'a, T>>,
Examples found in repository?
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<T: WithDType> NdArray<T>
impl<T: WithDType> NdArray<T>
Sourcepub fn broadcast_as<S: Into<Shape>>(&self, shape: S) -> Result<Self>
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>
impl<T: NumDType> NdArray<T>
Sourcepub fn broadcast_add(&self, rhs: &Self) -> Result<Self>
pub fn broadcast_add(&self, rhs: &Self) -> Result<Self>
pub fn broadcast_mul(&self, rhs: &Self) -> Result<Self>
pub fn broadcast_sub(&self, rhs: &Self) -> Result<Self>
pub fn broadcast_div(&self, rhs: &Self) -> Result<Self>
pub fn broadcast_maximum(&self, rhs: &Self) -> Result<Self>
pub fn broadcast_minimum(&self, rhs: &Self) -> Result<Self>
pub fn broadcast_eq(&self, rhs: &Self) -> Result<NdArray<bool>>
pub fn broadcast_ne(&self, rhs: &Self) -> Result<NdArray<bool>>
pub fn broadcast_lt(&self, rhs: &Self) -> Result<NdArray<bool>>
pub fn broadcast_le(&self, rhs: &Self) -> Result<NdArray<bool>>
pub fn broadcast_gt(&self, rhs: &Self) -> Result<NdArray<bool>>
pub fn broadcast_ge(&self, rhs: &Self) -> Result<NdArray<bool>>
Source§impl<From: WithDType> NdArray<From>
impl<From: WithDType> NdArray<From>
pub fn to_dtype<To: WithDType>(&self) -> NdArray<To>where
From: DTypeConvert<To>,
Source§impl<T: WithDType> NdArray<T>
impl<T: WithDType> NdArray<T>
pub fn filter(&self, conditions: &NdArray<bool>) -> Result<NdArray<T>>
Sourcepub fn select<TV, FV>(
mask: &NdArray<bool>,
true_val: TV,
false_val: FV,
) -> Result<Self>where
TV: ConditionValue<T>,
FV: ConditionValue<T>,
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?
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>
impl<T: WithDType> NdArray<T>
pub fn is_scalar(&self) -> bool
pub fn check_scalar(&self) -> Result<()>
pub fn to_scalar(&self) -> Result<T>
pub fn set_scalar(&self, val: T) -> Result<()>
pub fn storage_ref<'a>(&'a self, start_offset: usize) -> StorageRef<'a, T>
pub fn storage_mut<'a>(&'a self, start_offset: usize) -> StorageMut<'a, T>
pub fn storage_ptr(&self, start_offset: usize) -> *mut T
Source§impl<T: WithDType> NdArray<T>
impl<T: WithDType> NdArray<T>
pub fn id(&self) -> usize
Sourcepub fn shape(&self) -> &Shape
pub fn shape(&self) -> &Shape
Examples found in repository?
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}pub fn dtype(&self) -> DType
pub fn layout(&self) -> &Layout
pub fn dims(&self) -> &[usize]
pub fn dim<D: Dim>(&self, dim: D) -> Result<usize>
pub fn storage(&self) -> RwLockReadGuard<'_, Storage<T>>
pub fn element_count(&self) -> usize
pub fn is_contiguous(&self) -> bool
pub fn rank(&self) -> usize
pub fn to_vec(&self) -> Vec<T>
Sourcepub fn storage_indices(&self) -> StorageIndices<'_> ⓘ
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
Sourcepub fn dim_coordinates(&self) -> DimCoordinates ⓘ
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]
pub fn dims_coordinates<const N: usize>(&self) -> Result<DimNCoordinates<N>>
pub fn dim2_coordinates(&self) -> Result<DimNCoordinates<2>>
pub fn dim3_coordinates(&self) -> Result<DimNCoordinates<3>>
pub fn dim4_coordinates(&self) -> Result<DimNCoordinates<4>>
pub fn dim5_coordinates(&self) -> Result<DimNCoordinates<5>>
Source§impl<T: WithDType> NdArray<T>
impl<T: WithDType> NdArray<T>
pub fn matrix_view_unsafe(&self) -> Result<MatrixViewUsf<'_, T>>
pub fn vector_view_unsafe(&self) -> Result<VectorViewUsf<'_, T>>
pub fn matrix_view<'a>(&'a self) -> Result<MatrixView<'a, T>>
Sourcepub fn matrix_view_mut<'a>(&'a mut self) -> Result<MatrixViewMut<'a, T>>
pub fn matrix_view_mut<'a>(&'a mut self) -> Result<MatrixViewMut<'a, T>>
Examples found in repository?
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}