pub trait AsMatrix<'a, U: 'a> {
// Required methods
fn size(&self) -> (usize, usize);
fn at(&self, i: usize, j: usize) -> U;
}
Expand description
Defines a trait to handle Matrix-like data
§Example
use plotpy::AsMatrix;
fn sum<'a, T, U>(array: &'a T) -> f64
where
T: AsMatrix<'a, U>,
U: 'a + Into<f64>,
{
let mut res = 0.0;
let (m, n) = array.size();
for i in 0..m {
for j in 0..n {
res += array.at(i, j).into();
}
}
res
}
// heap-allocated 2D array (vector of vectors)
const IGNORED: f64 = 123.456;
let a = vec![
vec![1.0, 2.0],
vec![3.0, 4.0, IGNORED, IGNORED, IGNORED],
vec![5.0, 6.0],
];
assert_eq!(sum(&a), 21.0);
// heap-allocated 2D array (aka slice of slices)
let b: &[&[f64]] = &[
&[10.0, 20.0],
&[30.0, 40.0, IGNORED],
&[50.0, 60.0, IGNORED, IGNORED],
];
assert_eq!(sum(&b), 210.0);
// stack-allocated (fixed-size) 2D array
let c = [
[100.0, 200.0],
[300.0, 400.0],
[500.0, 600.0],
];
assert_eq!(sum(&c), 2100.0);
Required Methods§
Implementations on Foreign Types§
source§impl<'a, U> AsMatrix<'a, U> for &'a [&'a [U]]where
U: 'a + Copy,
impl<'a, U> AsMatrix<'a, U> for &'a [&'a [U]]where
U: 'a + Copy,
Defines a heap-allocated 2D array (slice of slices)
§Notes
- The number of columns is defined by the first row
- The next rows must have at least the same number of columns as the first row
source§impl<'a, U> AsMatrix<'a, U> for Vec<Vec<U>>where
U: 'a + Copy,
impl<'a, U> AsMatrix<'a, U> for Vec<Vec<U>>where
U: 'a + Copy,
Defines a heap-allocated 2D array (vector of vectors)
§Notes
- The number of columns is defined by the first row
- The next rows must have at least the same number of columns as the first row
source§impl<'a, U, const M: usize, const N: usize> AsMatrix<'a, U> for [[U; N]; M]where
U: 'a + Copy,
impl<'a, U, const M: usize, const N: usize> AsMatrix<'a, U> for [[U; N]; M]where
U: 'a + Copy,
Defines a stack-allocated (fixed-size) 2D array