### Configure BLAS integration with OpenBLAS Source: https://github.com/rust-ndarray/ndarray/blob/master/README.rst Example configuration for enabling BLAS support using the system OpenBLAS provider in Cargo.toml. ```toml [dependencies] ndarray = { version = "0.x.y", features = ["blas"] } blas-src = { version = "0.10", features = ["openblas"] } openblas-src = { version = "0.10", features = ["cblas", "system"] } ``` -------------------------------- ### Create and Use Array Views Source: https://context7.com/rust-ndarray/ndarray/llms.txt Demonstrates how to create immutable and mutable views of arrays to access data without cloning. Includes examples of slicing and creating views from standard slices. ```rust use ndarray::{array, ArrayView1, ArrayView2}; fn main() { let arr = array![ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0] ]; let view: ArrayView2 = arr.view(); println!("View shape: {:?}", view.shape()); let sub_view = view.slice(ndarray::s![.., 1..]); println!("Subview:\n{}", sub_view); let data = [1.0, 2.0, 3.0, 4.0]; let view_from_slice: ArrayView1 = ArrayView1::from(&data[..]); println!("From slice: {}", view_from_slice); let view1 = arr.view(); let view2 = arr.view(); println!("Sum of views: {}", view1.sum() + view2.sum()); } ``` -------------------------------- ### Iterate Over Elements Source: https://context7.com/rust-ndarray/ndarray/llms.txt Shows how to iterate over array elements using iter() and iter_mut(). Includes examples of indexed iteration to retrieve both position and value. ```rust use ndarray::array; fn main() { let arr = array![ [1, 2, 3], [4, 5, 6] ]; print!("Elements: "); for &elem in arr.iter() { print!("{} ", elem); } println!(); for ((row, col), &val) in arr.indexed_iter() { println!("[{}, {}] = {}", row, col, val); } let mut arr = arr; for elem in arr.iter_mut() { *elem *= 2; } println!("Doubled:\n{}", arr); } ``` -------------------------------- ### Iterate over rows and columns in ndarray Source: https://context7.com/rust-ndarray/ndarray/llms.txt Demonstrates how to use rows() and columns() methods to process 2D arrays. Includes examples for calculating sums, means, and performing in-place modifications. ```rust use ndarray::array; fn main() { let arr = array![ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0] ]; // Iterate over rows println!("Row sums:"); for (i, row) in arr.rows().into_iter().enumerate() { println!(" Row {}: sum = {}", i, row.sum()); } // Iterate over columns println!("Column means:"); for (i, col) in arr.columns().into_iter().enumerate() { let mean = col.sum() / col.len() as f64; println!(" Col {}: mean = {}", i, mean); } // Modify rows in-place let mut arr = arr; for (i, mut row) in arr.rows_mut().into_iter().enumerate() { row.mapv_inplace(|x| x + i as f64 * 10.0); } println!("Modified:\n{}", arr); } ``` -------------------------------- ### Rust: Generic Function Signature with LayoutRef and ?Sized Source: https://github.com/rust-ndarray/ndarray/blob/master/RELEASES.md Shows an example of a Rust function signature that accepts mutable references to types implementing `AsMut>` and includes the `+ ?Sized` bound. This allows the function to work with various array types, including `ArrayRef`. ```rust fn alter_shape(a: &mut T) where T: AsMut> + ?Sized; // Added bound here ``` -------------------------------- ### Mutable Slicing and Modification in Rust Source: https://context7.com/rust-ndarray/ndarray/llms.txt Demonstrates how to perform mutable slicing on ndarrays using `slice_mut` to modify portions of an array in-place. Examples include filling a subregion with a value, modifying elements with a step, and assigning data from another array to a slice. ```Rust use ndarray::{array, s}; fn main() { let mut arr = array![ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]; // Set a 2x2 subregion to 1 arr.slice_mut(s![0..2, 0..2]).fill(1); println!("After fill:\n{}", arr); // Output: // [[1, 1, 0, 0], // [1, 1, 0, 0], // [0, 0, 0, 0]] // Modify every other element in the last row arr.slice_mut(s![-1, ..;2]).fill(5); println!("After slice modify:\n{}", arr); // Assign from another array let src = array![9, 8, 7, 6]; arr.slice_mut(s![1, ..]).assign(&src); println!("After assign:\n{}", arr); } ``` -------------------------------- ### Rust ndarray Explicit Broadcasting to New Shape Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Shows how to explicitly broadcast an existing ndarray to a new shape using the `.broadcast()` method. This example broadcasts a 2x2 array to a 3x2x2 shape, repeating its elements. ```rust use ndarray::prelude::*; fn main() { let a = array![ [1., 2.], [3., 4.], ]; let b = a.broadcast((3, 2, 2)).unwrap(); println!("shape of a is {:?}", a.shape()); println!("a is broadcased to 3x2x2 = \n{}", b); } ``` -------------------------------- ### Direct Indexing of ndarrays in Rust Source: https://context7.com/rust-ndarray/ndarray/llms.txt Shows how to access and modify individual elements of ndarrays using direct indexing with square brackets `[]`. This method requires an index array matching the array's dimensionality and performs bounds checking in debug builds. It also demonstrates using `get` and `get_mut` for optional, non-panicking access. ```Rust use ndarray::{array, Array2, Array3}; fn main() { let mut arr = array![ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; // Read element at row 1, column 2 let val = arr[[1, 2]]; println!("Element at [1,2]: {}", val); // 6 // Write element arr[[0, 0]] = 100; println!("Modified array:\n{}", arr); // 3D indexing let arr3d = Array3::::zeros((2, 3, 4)); let _val = arr3d[[1, 2, 3]]; // Access element // Using get/get_mut for optional access (no panic on out-of-bounds) if let Some(val) = arr.get([1, 1]) { println!("Got value: {}", val); } if let Some(val) = arr.get_mut([2, 2]) { *val = 999; } } ``` -------------------------------- ### Create and Inspect 2D Array Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Demonstrates how to initialize a 2x3 floating-point array using the array! macro and inspect its properties such as dimensions, length, shape, and emptiness. ```rust use ndarray::prelude::*; fn main() { let a = array![ [1.,2.,3.], [4.,5.,6.], ]; assert_eq!(a.ndim(), 2); assert_eq!(a.len(), 6); assert_eq!(a.shape(), [2, 3]); assert_eq!(a.is_empty(), false); println!("{:?}", a); } ``` -------------------------------- ### Initialize Multi-dimensional Zeros Array Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Shows how to create a 3D array of zeros using explicit type annotation (turbofish) to satisfy Rust's type inference requirements. ```rust use ndarray::prelude::*; use ndarray::Array; fn main() { let a = Array::::zeros((3, 2, 4).f()); println!("{:?}", a); } ``` -------------------------------- ### Indexing and Slicing Arrays Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Demonstrates how to index, slice, and iterate over 1D and 3D arrays using the ndarray crate. ```APIDOC ## Indexing, Slicing, and Iterating ### Description Provides examples of accessing elements, slicing ranges, and iterating through multi-dimensional arrays. ### Method N/A (Library API) ### Endpoint ndarray::ArrayBase ### Parameters #### Path Parameters - **s![]** (macro) - Required - Slicing macro used to define ranges and indices. ### Request Example ```rust let a = array![[[0, 1, 2], [10, 12, 13]], [[100, 101, 102], [110, 112, 113]]]; let slice = a.slice(s![1, .., ..]); ``` ### Response #### Success Response (200) - **Array** (Object) - Returns a sliced view of the original array. #### Response Example ``` [[100, 101, 102], [110, 112, 113]] ``` ``` -------------------------------- ### Create Sequences with linspace, range, and logspace in Rust Source: https://context7.com/rust-ndarray/ndarray/llms.txt Illustrates creating arrays with evenly spaced values using `linspace`, `range`, and `logspace`. These are essential for generating coordinate grids, time series, or logarithmic scales in scientific computing. ```Rust use ndarray::Array; fn main() { // Create 11 evenly spaced values from 0.0 to 5.0 (inclusive) let linspace = Array::::linspace(0.0..=5.0, 11); println!("Linspace: {}", linspace); // Output: [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5] // Create values from 0 to 5 (exclusive) with step 1 let range = Array::range(0., 5., 1.); println!("Range: {}", range); // Output: [0, 1, 2, 3, 4] // Create logarithmically spaced values: 10^0 to 10^3 let logspace = Array::logspace(10.0, 0.0..=3.0, 4); println!("Logspace: {}", logspace); // Output: [1, 10, 100, 1000] // Geometric spacing from 1 to 1000 if let Some(geomspace) = Array::geomspace(1.0, 1000.0, 4) { println!("Geomspace: {}", geomspace); // Output: [1, 10, 100, 1000] } } ``` -------------------------------- ### Splitting Arrays into Views Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Shows how to split an array into multiple smaller views using the split_at method. This operation is efficient as it creates views rather than copying the underlying data. ```rust use ndarray::prelude::*; use ndarray::Axis; fn main() { let a = array![[6., 7., 6., 9., 0., 5., 4., 0., 6., 8., 5., 2.], [8., 5., 5., 7., 1., 8., 6., 7., 1., 8., 1., 0.]]; let (s1, s2) = a.view().split_at(Axis(0), 1); println!("Split a from Axis(0), at index 1:\ns1 = \n{}\ns2 = \n{}\n", s1, s2); let (s1, s2) = a.view().split_at(Axis(1), 4); println!("Split a from Axis(1), at index 4:\ns1 = \n{}\ns2 = \n{}\n", s1, s2); } ``` -------------------------------- ### Map functions over array elements Source: https://context7.com/rust-ndarray/ndarray/llms.txt Demonstrates mapping functions over arrays using map, mapv, and mapv_inplace. Highlights the performance benefits of mapv for Copy types. ```rust use ndarray::array; fn main() { let arr = array![[1.0, 4.0, 9.0], [16.0, 25.0, 36.0]]; // map: applies function to references, returns new array let sqrt = arr.map(|&x| x.sqrt()); println!("Square roots:\n{}", sqrt); // mapv: applies function to values (more efficient for Copy types) let squared = arr.mapv(|x| x * x); println!("Squared:\n{}", squared); // mapv_inplace: modify in place let mut arr = arr; arr.mapv_inplace(|x| x.ln()); println!("Natural log:\n{}", arr); // map_inplace with index let mut indexed = array![[0, 0, 0], [0, 0, 0]]; indexed.indexed_iter_mut().for_each(|((i, j), elem)| { *elem = (i * 10 + j) as i32; }); println!("Indexed:\n{}", indexed); } ``` -------------------------------- ### Manage Mutable Views and Ownership Source: https://context7.com/rust-ndarray/ndarray/llms.txt Explains how to perform in-place modifications using mutable views while adhering to Rust's borrowing rules. Shows how to split arrays into multiple mutable sections. ```rust use ndarray::{array, s, Axis}; fn main() { let mut arr = array![ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; { let mut view = arr.slice_mut(s![..2, ..]); view.fill(0); } println!("After mutable view:\n{}", arr); let (top, bottom) = arr.view_mut().split_at(Axis(0), 2); println!("Top:\n{}", top); println!("Bottom:\n{}", bottom); } ``` -------------------------------- ### Managing Array Views and Ownership Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Illustrates the relationship between array views and ownership in Rust. It demonstrates how views restrict mutation of the original array until the views go out of scope. ```rust use ndarray::prelude::*; use ndarray::{Array, Axis}; fn main() { let mut a = Array::range(0., 12., 1.).into_shape_with_order([3 ,4]).unwrap(); { let (s1, s2) = a.view().split_at(Axis(1), 2); println!("s1 = \n{}\ns2 = \n{}\n", s1, s2); } a.slice_mut(s![1, 1]).fill(1234.); let (s1, s2) = a.view().split_at(Axis(1), 2); println!("Updated s1 = \n{}\ns2 = \n{}\n", s1, s2); } ``` -------------------------------- ### Creating ndarrays from Shape and Data in Rust Source: https://context7.com/rust-ndarray/ndarray/llms.txt Demonstrates how to create multi-dimensional arrays (2D and 3D) from flat vectors using `from_shape_vec`. It also shows how to specify Fortran order (column-major) for array layout. This method allows precise control over array dimensions and data population. ```Rust use ndarray::{Array, Array2, Array3}; fn main() { // Create a 2x3 array from flat data let data = vec![1, 2, 3, 4, 5, 6]; let arr = Array2::from_shape_vec((2, 3), data).unwrap(); println!("2x3 array:\n{}", arr); // Output: // [[1, 2, 3], // [4, 5, 6]] // Create 3D array (2x2x3) let data_3d = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; let arr_3d = Array3::from_shape_vec((2, 2, 3), data_3d).unwrap(); println!("3D array shape: {:?}", arr_3d.shape()); // Output: [2, 2, 3] // Create with Fortran order (column-major) let data = vec![1, 4, 2, 5, 3, 6]; let arr_f = Array2::from_shape_vec((2, 3).f(), data).unwrap(); println!("F-order array:\n{}", arr_f); } ``` -------------------------------- ### Create 1D Array with Linspace Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Demonstrates the creation of a 1D array using the linspace method to generate evenly spaced values within a specified range. ```rust use ndarray::prelude::*; use ndarray::{Array, Ix3}; fn main() { let a = Array::::linspace(0.0..=5.0, 11); println!("{:?}", a); } ``` -------------------------------- ### Stacking and Concatenating Arrays Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Demonstrates how to use the stack! and concatenate! macros to combine arrays. The stack! macro creates a new axis, while concatenate! joins arrays along an existing axis. ```rust use ndarray::prelude::*; use ndarray::{concatenate, stack, Axis}; fn main() { let a = array![[3., 7., 8.], [5., 2., 4.]]; let b = array![[1., 9., 0.], [5., 4., 1.]]; println!("stack, axis 0:\n{:?}\n", stack![Axis(0), a, b]); println!("stack, axis 1:\n{:?}\n", stack![Axis(1), a, b]); println!("stack, axis 2:\n{:?}\n", stack![Axis(2), a, b]); println!("concatenate, axis 0:\n{:?}\n", concatenate![Axis(0), a, b]); println!("concatenate, axis 1:\n{:?}\n", concatenate![Axis(1), a, b]); } ``` -------------------------------- ### Create 2D Identity and Diagonal Matrices in Rust Source: https://context7.com/rust-ndarray/ndarray/llms.txt Demonstrates creating identity matrices and matrices with specified diagonal elements using `eye`, `from_diag`, and `from_diag_elem`. These are crucial for various linear algebra operations. ```Rust use ndarray::{Array2, arr1}; fn main() { // Create a 4x4 identity matrix let identity: Array2 = Array2::eye(4); println!("Identity:\n{}", identity); // Create matrix from diagonal vector let diag = arr1(&[1, 2, 3, 4]); let diag_matrix = Array2::from_diag(&diag); println!("From diagonal:\n{}", diag_matrix); // Output: // [[1, 0, 0, 0], // [0, 2, 0, 0], // [0, 0, 3, 0], // [0, 0, 0, 4]] // Create diagonal matrix with constant element let scaled_identity = Array2::from_diag_elem(3, 5.0); println!("Scaled identity:\n{}", scaled_identity); // Output: // [[5, 0, 0], // [0, 5, 0], // [0, 0, 5]] } ``` -------------------------------- ### Array Creation and Initialization Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Methods for creating and initializing ndarrays with specific dimensions, types, and values. ```APIDOC ## Array Creation Methods ### Description This section covers the initialization of ndarrays using various constructors like `zeros`, `from_elem`, and `linspace`. ### Methods - `Array::zeros(shape)`: Creates an array of the specified shape filled with zeros. - `Array::from_elem(shape, value)`: Creates an array of the specified shape filled with a given value. - `Array::linspace(start..=end, count)`: Creates a 1-D array with evenly spaced values. ### Examples #### Creating a 2x3 Array ```rust use ndarray::prelude::*; let a = array![[1., 2., 3.], [4., 5., 6.]]; ``` #### Creating a 3D Array with Zeros ```rust use ndarray::prelude::*; let a = Array::::zeros((3, 2, 4).f()); ``` #### Creating a 1-D Array with linspace ```rust use ndarray::prelude::*; let a = Array::::linspace(0.0..=5.0, 11); ``` ``` -------------------------------- ### Convenient Element-wise Operations with ndarray azip! Macro Source: https://context7.com/rust-ndarray/ndarray/llms.txt The azip! macro provides a concise, for-loop-like syntax for common Zip operations in ndarray. It simplifies element-wise computations, allowing for direct manipulation of array elements within a loop structure. This macro requires the ndarray crate. ```Rust use ndarray::{array, Array2, azip}; fn main() { let a = array![[1.0, 2.0], [3.0, 4.0]]; let b = array![[0.5, 1.5], [2.5, 3.5]]; let mut c = Array2::::zeros((2, 2)); // azip! for element-wise computation azip!((c in &mut c, &a in &a, &b in &b) { *c = (a + b) / 2.0; }); println!("Average:\n{}", c); // Multiple operations in one pass let mut sum = 0.0; let mut count = 0; azip!((&a in &a) { sum += a; count += 1; }); println!("Mean: {}", sum / count as f64); } ``` -------------------------------- ### Generate Random Arrays with Probability Distributions Source: https://context7.com/rust-ndarray/ndarray/llms.txt This snippet demonstrates how to create arrays filled with random values using Uniform and Normal distributions. It also shows how to use a seeded RNG to ensure reproducible results for testing or simulation purposes. ```rust use ndarray::Array; use ndarray_rand::RandomExt; use ndarray_rand::rand_distr::{Uniform, Normal, StandardNormal}; fn main() { let uniform = Array::random((3, 4), Uniform::new(0.0, 10.0).unwrap()); println!("Uniform [0, 10):\n{:.2}", uniform); let normal: ndarray::Array2 = Array::random((3, 4), StandardNormal); println!("Standard normal:\n{:.2}", normal); let custom_normal = Array::random((3, 4), Normal::new(5.0, 2.0).unwrap()); println!("Normal(5, 2):\n{:.2}", custom_normal); use ndarray_rand::rand::SeedableRng; use ndarray_rand::rand::rngs::SmallRng; let mut rng = SmallRng::seed_from_u64(42); let reproducible = Array::random_using((2, 3), Uniform::new(0, 100).unwrap(), &mut rng); println!("Reproducible:\n{}", reproducible); } ``` -------------------------------- ### Performing Deep Copies with Clone Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Demonstrates how to perform a deep copy of an array using the clone() method. Unlike views, a cloned array owns its data independently. ```rust use ndarray::prelude::*; use ndarray::Array; fn main() { let mut a = Array::range(0., 4., 1.).into_shape_with_order([2 ,2]).unwrap(); let b = a.clone(); a.slice_mut(s![1, 1]).fill(1234.); println!("a updated: \n{}\n", a); println!("b (clone) remains unchanged: \n{}\n", b); } ``` -------------------------------- ### Perform Matrix Multiplication in ndarray Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Shows how to perform matrix dot products using the dot method. It also demonstrates how to reshape arrays to ensure compatible dimensions for matrix multiplication. ```rust use ndarray::prelude::*;\nuse ndarray::Array;\n\nfn main() {\n let a = array![[10.,20.,30., 40.,]];\n let b = Array::range(0., 4., 1.);\n let b = b.into_shape_with_order((4,1)).unwrap();\n println!("{}", a.dot(&b));\n println!("{}", a.t().dot(&b.t()));\n} ``` -------------------------------- ### Rust ndarray: Indexing, Slicing, and Iterating 1D Arrays Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Demonstrates indexing, slicing, and iterating over one-dimensional arrays in Rust using the ndarray crate. It shows how to access elements, subarrays, and iterate through array elements, with operations analogous to NumPy. ```rust use ndarray::prelude::*; use ndarray::Array; fn main() { let a = Array::range(0., 10., 1.); let mut a = a.mapv(|a: f64| a.powi(3)); // numpy equivlant of `a ** 3`; https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.powi println!("{}", a); println!("{}", a[[2]]); println!("{}", a.slice(s![2])); println!("{}", a.slice(s![2..5])); a.slice_mut(s![..6;2]).fill(1000.); // numpy equivlant of `a[:6:2] = 1000` println!("{}", a); for i in a.iter() { print!("{}, ", i.powf(1./3.)) } } ``` -------------------------------- ### Dot Product and Matrix Multiplication in Rust ndarray Source: https://context7.com/rust-ndarray/ndarray/llms.txt Explains how to perform dot products for vectors and matrix multiplications for matrices using the `dot()` method. It covers vector-vector, matrix-vector, and matrix-matrix multiplication scenarios. ```rust use ndarray::{array, Array1, Array2}; fn main() { // Vector dot product let v1 = array![1.0, 2.0, 3.0]; let v2 = array![4.0, 5.0, 6.0]; let dot_product = v1.dot(&v2); println!("Dot product: {}", dot_product); // 32.0 = 1*4 + 2*5 + 3*6 // Matrix-vector multiplication let matrix = array![ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0] ]; let vector = array![1.0, 2.0, 3.0]; let result = matrix.dot(&vector); println!("Matrix-vector: {}", result); // [14, 32] // Matrix-matrix multiplication let a = array![[1.0, 2.0], [3.0, 4.0]]; let b = array![[5.0, 6.0], [7.0, 8.0]]; let c = a.dot(&b); println!("Matrix product:\n{}", c); // Output: // [[19, 22], // [43, 50]] // Vector-matrix multiplication (row vector) let row_vec = array![1.0, 2.0]; let result = row_vec.dot(&a); println!("Row-matrix: {}", result); // [7, 10] } ``` -------------------------------- ### Initialize Array with Custom Value Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Uses the from_elem method to create a 3D boolean array initialized to a specific value. ```rust use ndarray::{Array, Ix3}; fn main() { let a = Array::::from_elem((3, 2, 4), false); println!("{:?}", a); } ``` -------------------------------- ### Basic Slicing with s![] Macro in Rust Source: https://context7.com/rust-ndarray/ndarray/llms.txt Explains how to use the `s![]` macro to create slice specifications for extracting subarrays from ndarrays. It covers various slicing techniques including ranges, steps, negative indices, and combining these for flexible data access. This allows for efficient extraction of sub-regions without copying data. ```Rust use ndarray::{array, s}; fn main() { let arr = array![ [ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20] ]; // Slice rows 1-2 (exclusive), all columns let slice1 = arr.slice(s![1..3, ..]); println!("Rows 1-2:\n{}", slice1); // Output: [[6, 7, 8, 9, 10], [11, 12, 13, 14, 15]] // Slice all rows, columns 1-3 let slice2 = arr.slice(s![.., 1..4]); println!("Columns 1-3:\n{}", slice2); // Every other row, every other column let slice3 = arr.slice(s![..;2, ..;2]); println!("Every other:\n{}", slice3); // Output: [[1, 3, 5], [11, 13, 15]] // Negative indices: last row, last 3 columns let slice4 = arr.slice(s![-1, -3..]); println!("Last row, last 3 cols: {}", slice4); // Output: [18, 19, 20] // Reverse a dimension with negative step let reversed = arr.slice(s![..;-1, ..]); println!("Reversed rows:\n{}", reversed); } ``` -------------------------------- ### Transpose Arrays Source: https://context7.com/rust-ndarray/ndarray/llms.txt Demonstrates zero-copy transposition of arrays using the t() method and reversing axes for multi-dimensional arrays. ```rust use ndarray::array; fn main() { let arr = array![ [1, 2, 3], [4, 5, 6] ]; println!("Original (2x3):\n{}", arr); let transposed = arr.t(); println!("Transposed (3x2):\n{}", transposed); let arr3d = array![ [[1, 2], [3, 4]], [[5, 6], [7, 8]] ]; println!("3D shape: {:?}", arr3d.shape()); let reversed = arr3d.view().reversed_axes(); println!("Reversed shape: {:?}", reversed.shape()); } ``` -------------------------------- ### Shape Manipulation Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Demonstrates how to change the shape of an array using into_shape_with_order. ```APIDOC ## Shape Manipulation ### Description Methods to reshape arrays, such as converting a matrix into a flat vector or changing dimensions. ### Method N/A (Library API) ### Endpoint ndarray::ArrayBase::into_shape_with_order ### Parameters #### Request Body - **shape** (Array/Tuple) - Required - The target dimensions for the new array. ### Request Example ```rust let c = b.into_shape_with_order([6, 2]).unwrap(); ``` ### Response #### Success Response (200) - **Array** (Object) - Returns a new array with the specified shape. #### Response Example ``` [[3.0, 7.0], [3.0, 4.0], [1.0, 4.0], [2.0, 2.0], [7.0, 2.0], [4.0, 9.0]] ``` ``` -------------------------------- ### Rust: Using ArrayRef for General Array Access Source: https://github.com/rust-ndarray/ndarray/blob/master/RELEASES.md Demonstrates how to use the new `ArrayRef` type in Rust for reading and writing elements of any ndarray array. `ArrayRef` provides a consistent interface similar to `&[T]` for owned arrays and views, simplifying function signatures. ```rust fn sum(a: &ArrayRef1) -> f64; fn cumsum_mut(a: &mut ArrayRef1); ``` -------------------------------- ### Perform Element-wise Arithmetic Operations in ndarray Source: https://github.com/rust-ndarray/ndarray/blob/master/README-quick-start.md Demonstrates how to perform element-wise addition, subtraction, multiplication, and division on ndarray arrays. It highlights the importance of using references to manage memory allocation and ownership during binary operations. ```rust use ndarray::prelude::*;\nuse ndarray::Array;\nuse std::f64::INFINITY as inf;\n\nfn main() {\n let a = array![[10.,20.,30., 40.,]];\n let b = Array::range(0., 4., 1.);\n\n assert_eq!(&a + &b, array![[10., 21., 32., 43.,]]);\n assert_eq!(&a - &b, array![[10., 19., 28., 37.,]]);\n assert_eq!(&a * &b, array![[0., 20., 60., 120.,]]);\n assert_eq!(&a / &b, array![[inf, 20., 15., 13.333333333333334,]]);\n} ``` -------------------------------- ### Explicit Broadcasting in Rust ndarray Source: https://context7.com/rust-ndarray/ndarray/llms.txt Demonstrates how to use the `broadcast()` method to expand an array's shape without copying data. It shows broadcasting for display and for computational purposes, highlighting the resulting shapes and content. ```rust use ndarray::{array, Array2}; fn main() { let small = array![[1.0, 2.0]]; println!("Original shape: {:?}", small.shape()); // [1, 2] // Broadcast to 3x2 let broadcasted = small.broadcast((3, 2)).unwrap(); println!("Broadcasted shape: {:?}", broadcasted.shape()); // [3, 2] println!("Broadcasted:\n{}", broadcasted); // Output: // [[1, 2], // [1, 2], // [1, 2]] // Broadcast for computation let matrix: Array2 = Array2::ones((3, 2)) * 10.0; let result = &matrix * &broadcasted; println!("Result:\n{}", result); } ``` -------------------------------- ### Rust: Inspecting Array Layout with LayoutRef Source: https://github.com/rust-ndarray/ndarray/blob/master/RELEASES.md Illustrates using `LayoutRef` in Rust to inspect or modify shape and stride information of an ndarray without accessing the data. This approach is useful for functions that only need layout details and requires a `+ ?Sized` bound for broader compatibility. ```rust fn alter_shape(a: &mut T) where T: AsMut> + ?Sized; ``` -------------------------------- ### Rust: PartialEq Implementation for ArrayRef and ArrayBase Source: https://github.com/rust-ndarray/ndarray/blob/master/RELEASES.md This code snippet represents the implementation of `PartialEq` for comparing `ArrayRef` and `ArrayBase` types in Rust. This allows for direct equality checks between different array reference and base types. ```rust // This represents the addition of PartialEq implementations // between ArrayRef and ArrayBase. // Example: // let arr_ref: ArrayRef = ...; // let arr_base: ArrayBase = ...; // assert!(arr_ref == arr_base); ``` -------------------------------- ### Create ndarrays with Constant Values in Rust Source: https://context7.com/rust-ndarray/ndarray/llms.txt Shows how to create ndarrays filled with constant values like zeros, ones, or a specific element. These methods are useful for initializing arrays before populating them with computed data. ```Rust use ndarray::{Array, Array2, Array3, Ix3}; fn main() { // Create a 3x4 matrix of zeros let zeros: Array2 = Array2::zeros((3, 4)); println!("Zeros:\n{}", zeros); // Create a 2x3 matrix of ones let ones: Array2 = Array2::ones((2, 3)); println!("Ones:\n{}", ones); // Create array filled with a specific value let filled = Array::::from_elem((2, 3, 4), false); println!("Filled shape: {:?}", filled.shape()); // Output: [2, 3, 4] // Create with Fortran (column-major) memory order using .f() let f_order = Array::::zeros((3, 2, 4).f()); println!("F-order layout: {:?}", f_order.strides()); } ``` -------------------------------- ### Demonstrate ArrayView Lifetime Covariance Source: https://github.com/rust-ndarray/ndarray/blob/master/RELEASES.md This snippet demonstrates how ArrayView is now covariant over its lifetime, allowing a static lifetime array view to be passed where a shorter lifetime is expected. ```rust fn fn_cov<'a>(x: ArrayView1<'static, f64>) -> ArrayView1<'a, f64> { x } ``` -------------------------------- ### General Matrix Multiplication in Rust ndarray Source: https://context7.com/rust-ndarray/ndarray/llms.txt Shows how to use the `general_mat_mul` function for more complex matrix multiplication operations, including accumulated results. It demonstrates the `C = α * A × B + β * C` formula. ```rust use ndarray::{array, Array2}; use ndarray::linalg::general_mat_mul; fn main() { let a = array![[1.0, 2.0], [3.0, 4.0]]; let b = array![[5.0, 6.0], [7.0, 8.0]]; let mut c = array![[1.0, 1.0], [1.0, 1.0]]; // Compute C = 1.0 * A × B + 2.0 * C general_mat_mul(1.0, &a, &b, 2.0, &mut c); println!("Result:\n{}", c); // C = [[19, 22], [43, 50]] + [[2, 2], [2, 2]] = [[21, 24], [45, 52]] } ``` -------------------------------- ### Linear Algebra Operations Source: https://context7.com/rust-ndarray/ndarray/llms.txt Routines for dot products and matrix multiplication. ```APIDOC ## POST /linalg/dot ### Description Computes the dot product of two arrays or matrix multiplication. ### Method POST ### Endpoint /linalg/dot ### Parameters #### Request Body - **a** (Array) - Required - First operand - **b** (Array) - Required - Second operand ### Request Example { "a": [[1.0, 2.0]], "b": [[3.0], [4.0]] } ### Response #### Success Response (200) - **result** (Array) - The dot product result #### Response Example { "result": [11.0] } ``` -------------------------------- ### Configure ndarray without standard library Source: https://github.com/rust-ndarray/ndarray/blob/master/README.rst Shows how to disable the default 'std' feature in Cargo.toml for environments without the Rust standard library. ```toml [dependencies] ndarray = { version = "0.x.y", default-features = false } ``` -------------------------------- ### Reduction Operations in Rust ndarray Source: https://context7.com/rust-ndarray/ndarray/llms.txt Illustrates various reduction operations including sum, product, and mean, both globally across all elements and along specific axes (rows or columns). It also covers variance and standard deviation calculations. ```rust use ndarray::{array, Axis}; fn main() { let arr = array![ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0] ]; // Global reductions println!("Sum: {}", arr.sum()); // 21.0 println!("Product: {}", arr.product()); // 720.0 println!("Mean: {:?}", arr.mean()); // Some(3.5) // Reductions along axis let row_sums = arr.sum_axis(Axis(1)); println!("Row sums: {}", row_sums); // [6, 15] let col_sums = arr.sum_axis(Axis(0)); println!("Column sums: {}", col_sums); // [5, 7, 9] let col_means = arr.mean_axis(Axis(0)).unwrap(); println!("Column means: {}", col_means); // [2.5, 3.5, 4.5] // Product along axis let row_products = arr.product_axis(Axis(1)); println!("Row products: {}", row_products); // [6, 120] } ``` ```rust use ndarray::{array, Axis}; fn main() { let arr = array![ [2.0, 4.0, 6.0], [8.0, 10.0, 12.0] ]; // Population variance (ddof=0) let pop_var = arr.var(0.0); println!("Population variance: {}", pop_var); // Sample variance (ddof=1) let sample_var = arr.var(1.0); println!("Sample variance: {}", sample_var); // Standard deviation let std_dev = arr.std(1.0); println!("Sample std dev: {}", std_dev); // Variance along axis let col_var = arr.var_axis(Axis(0), 0.0); println!("Column variances: {}", col_var); // Std deviation along axis let row_std = arr.std_axis(Axis(1), 1.0); println!("Row std devs: {}", row_std); } ``` -------------------------------- ### Create 1D ndarray from Vector and Iterator in Rust Source: https://context7.com/rust-ndarray/ndarray/llms.txt Demonstrates creating one-dimensional ndarrays from existing vectors and iterators. These are fundamental methods for initializing arrays with data already in memory or generated on the fly. ```Rust use ndarray::Array; fn main() { // Create array from a vector let arr = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0]); println!("From vec: {}", arr); // Output: [1, 2, 3, 4, 5] // Create array from an iterator let arr = Array::from_iter(0..10); println!("From iter: {}", arr); // Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] // Create from iterator with transformation let squares = Array::from_iter((1..=5).map(|x| x * x)); println!("Squares: {}", squares); // Output: [1, 4, 9, 16, 25] } ``` -------------------------------- ### Using the array! Macro for Literal Array Creation in Rust Source: https://context7.com/rust-ndarray/ndarray/llms.txt Illustrates the use of the `array!` macro for creating multi-dimensional arrays with a literal syntax, similar to `vec![]`. It supports 1D, 2D, and 3D arrays and provides alternative constructors like `arr1`, `arr2`, and `arr3` for creating arrays from slices. ```Rust use ndarray::{array, arr1, arr2, arr3}; fn main() { // 1D array let a = array![1, 2, 3, 4, 5]; println!("1D: {}", a); // 2D array (matrix) let b = array![ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0] ]; println!("2D:\n{}", b); println!("Shape: {:?}", b.shape()); // [2, 3] // 3D array let c = array![ [[1, 2], [3, 4]], [[5, 6], [7, 8]] ]; println!("3D shape: {:?}", c.shape()); // [2, 2, 2] // Alternative constructors let d = arr1(&[1, 2, 3]); // 1D from slice let e = arr2(&[[1, 2], [3, 4]]); // 2D from nested slice let f = arr3(&[[[1], [2]], [[3], [4]]]); // 3D from nested slice } ```