pub trait BaseMatrix<T>: Sized {
Show 30 methods
// Required methods
fn rows(&self) -> usize;
fn cols(&self) -> usize;
fn row_stride(&self) -> usize;
fn as_ptr(&self) -> *const T;
// Provided methods
fn is_empty(&self) -> bool { ... }
fn as_slice(&self) -> MatrixSlice<'_, T> { ... }
unsafe fn get_unchecked(&self, index: [usize; 2]) -> &T { ... }
fn get_row(&self, index: usize) -> Option<&[T]> { ... }
unsafe fn get_row_unchecked(&self, index: usize) -> &[T] { ... }
fn iter<'a>(&self) -> SliceIter<'a, T>
where T: 'a { ... }
fn iter_rows(&self) -> Rows<'_, T> { ... }
fn iter_diag(&self, k: DiagOffset) -> Diagonal<'_, T, Self> { ... }
fn sum_rows(&self) -> Vector<T>
where T: Copy + Zero<Output = T> + Add { ... }
fn sum_cols(&self) -> Vector<T>
where T: Copy + Zero<Output = T> + Add { ... }
fn sum(&self) -> T
where T: Copy + Zero<Output = T> + Add { ... }
fn into_matrix(self) -> Matrix<T>
where T: Copy { ... }
fn select_rows<'a, I>(&self, rows: I) -> Matrix<T>
where T: Copy,
I: IntoIterator<Item = &'a usize>,
<I as IntoIterator>::IntoIter: ExactSizeIterator + Clone { ... }
fn select_cols<'a, I>(&self, cols: I) -> Matrix<T>
where T: Copy,
I: IntoIterator<Item = &'a usize>,
<I as IntoIterator>::IntoIter: ExactSizeIterator + Clone { ... }
fn elemul(&self, m: &Self) -> Matrix<T>
where T: Copy + Mul<Output = T> { ... }
fn elediv(&self, m: &Self) -> Matrix<T>
where T: Copy + Div<Output = T> { ... }
fn select(&self, rows: &[usize], cols: &[usize]) -> Matrix<T>
where T: Copy { ... }
fn hcat<S>(&self, m: &S) -> Matrix<T>
where T: Copy,
S: BaseMatrix<T> { ... }
fn vcat<S>(&self, m: &S) -> Matrix<T>
where T: Copy,
S: BaseMatrix<T> { ... }
fn diag(&self) -> Vector<T>
where T: Copy { ... }
fn transpose(&self) -> Matrix<T>
where T: Copy { ... }
fn is_diag(&self) -> bool
where T: Zero + PartialEq { ... }
fn solve_u_triangular(&self, y: Vector<T>) -> Result<Vector<T>, Error>
where T: Any + Float { ... }
fn solve_l_triangular(&self, y: Vector<T>) -> Result<Vector<T>, Error>
where T: Any + Float { ... }
fn split_at(
&self,
mid: usize,
axis: Axes,
) -> (MatrixSlice<'_, T>, MatrixSlice<'_, T>) { ... }
fn sub_slice<'a>(
&self,
start: [usize; 2],
rows: usize,
cols: usize,
) -> MatrixSlice<'a, T>
where T: 'a { ... }
}Expand description
Trait for immutable matrix structs.
Required Methods§
Sourcefn row_stride(&self) -> usize
fn row_stride(&self) -> usize
Row stride in the matrix.
Provided Methods§
Sourcefn as_slice(&self) -> MatrixSlice<'_, T>
fn as_slice(&self) -> MatrixSlice<'_, T>
Returns a MatrixSlice over the whole matrix.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(3, 3, vec![2.0; 9]);
let b = a.as_slice();Sourceunsafe fn get_unchecked(&self, index: [usize; 2]) -> &T
unsafe fn get_unchecked(&self, index: [usize; 2]) -> &T
Get a reference to a point in the matrix without bounds checking.
Sourcefn get_row(&self, index: usize) -> Option<&[T]>
fn get_row(&self, index: usize) -> Option<&[T]>
Returns the row of a matrix at the given index.
None if the index is out of bounds.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(3,3, (0..9).collect::<Vec<usize>>());
let slice = a.sub_slice([1,1], 2, 2);
let row = slice.get_row(1);
let expected = vec![7usize, 8];
assert_eq!(row, Some(&*expected));
assert!(slice.get_row(5).is_none());Sourceunsafe fn get_row_unchecked(&self, index: usize) -> &[T]
unsafe fn get_row_unchecked(&self, index: usize) -> &[T]
Returns the row of a matrix at the given index without doing unbounds checking
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(3,3, (0..9).collect::<Vec<usize>>());
let slice = a.sub_slice([1,1], 2, 2);
let row = unsafe { slice.get_row_unchecked(1) };
let mut expected = vec![7usize, 8];
assert_eq!(row, &*expected);Sourcefn iter<'a>(&self) -> SliceIter<'a, T>where
T: 'a,
fn iter<'a>(&self) -> SliceIter<'a, T>where
T: 'a,
Returns an iterator over the matrix data.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(3,3, (0..9).collect::<Vec<usize>>());
let slice = a.sub_slice([1,1], 2, 2);
let slice_data = slice.iter().map(|v| *v).collect::<Vec<usize>>();
assert_eq!(slice_data, vec![4,5,7,8]);Sourcefn iter_rows(&self) -> Rows<'_, T>
fn iter_rows(&self) -> Rows<'_, T>
Iterate over the rows of the matrix.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(3, 2, (0..6).collect::<Vec<usize>>());
// Prints "2" three times.
for row in a.iter_rows() {
println!("{}", row.len());
}Examples found in repository?
12fn generate_data(centroids: &Matrix<f64>,
13 points_per_centroid: usize,
14 noise: f64)
15 -> Matrix<f64> {
16 assert!(centroids.cols() > 0, "Centroids cannot be empty.");
17 assert!(centroids.rows() > 0, "Centroids cannot be empty.");
18 assert!(noise >= 0f64, "Noise must be non-negative.");
19 let mut raw_cluster_data = Vec::with_capacity(centroids.rows() * points_per_centroid *
20 centroids.cols());
21
22 let mut rng = thread_rng();
23 let normal_rv = Normal::new(0f64, noise);
24
25 for _ in 0..points_per_centroid {
26 // Generate points from each centroid
27 for centroid in centroids.iter_rows() {
28 // Generate a point randomly around the centroid
29 let mut point = Vec::with_capacity(centroids.cols());
30 for feature in centroid {
31 point.push(feature + normal_rv.ind_sample(&mut rng));
32 }
33
34 // Push point to raw_cluster_data
35 raw_cluster_data.extend(point);
36 }
37 }
38
39 Matrix::new(centroids.rows() * points_per_centroid,
40 centroids.cols(),
41 raw_cluster_data)
42}More examples
121fn main() {
122 let (training_set_size, test_set_size) = (1000, 1000);
123 // Generate all of our train and test data
124 let (training_matrix, target_matrix, test_matrix, test_dogs) = generate_dog_data(training_set_size, test_set_size);
125
126 // Train!
127 let mut model = NaiveBayes::<naive_bayes::Gaussian>::new();
128 model.train(&training_matrix, &target_matrix)
129 .expect("failed to train model of dogs");
130
131 // Predict!
132 let predictions = model.predict(&test_matrix)
133 .expect("failed to predict dogs!?");
134
135 // Score how well we did.
136 let mut hits = 0;
137 let unprinted_total = test_set_size.saturating_sub(10) as usize;
138 for (dog, prediction) in test_dogs.iter().zip(predictions.iter_rows()).take(unprinted_total) {
139 evaluate_prediction(&mut hits, dog, prediction);
140 }
141
142 if unprinted_total > 0 {
143 println!("...");
144 }
145
146 for (dog, prediction) in test_dogs.iter().zip(predictions.iter_rows()).skip(unprinted_total) {
147 let (actual_color, accurate) = evaluate_prediction(&mut hits, dog, prediction);
148 println!("Predicted: {:?}; Actual: {:?}; Accurate? {:?}",
149 dog.color, actual_color, accurate);
150 }
151
152 println!("Accuracy: {}/{} = {:.1}%", hits, test_set_size,
153 (f64::from(hits))/(f64::from(test_set_size)) * 100.);
154}Sourcefn iter_diag(&self, k: DiagOffset) -> Diagonal<'_, T, Self>
fn iter_diag(&self, k: DiagOffset) -> Diagonal<'_, T, Self>
Iterate over diagonal entries
§Examples
use rulinalg::matrix::{DiagOffset, Matrix, BaseMatrix};
let a = matrix![0, 1, 2;
3, 4, 5;
6, 7, 8];
// Print super diag [1, 5]
for d in a.iter_diag(DiagOffset::Above(1)) {
println!("{}", d);
}
// Print sub diag [3, 7]
// Equivalent to `iter_diag(DiagOffset::Below(1))`
for d in a.iter_diag(DiagOffset::from(-1)) {
println!("{}", d);
}§Panics
If using an Above or Below offset which is
out-of-bounds this function will panic.
This function will never panic if the Main diagonal
offset is used.
Sourcefn sum_rows(&self) -> Vector<T>
fn sum_rows(&self) -> Vector<T>
The sum of the rows of the matrix.
Returns a Vector equal to the sums of elements over the matrices rows.
Note that the resulting vector is identical to the sums of elements along each column of the matrix.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(2,2,vec![1.0,2.0,3.0,4.0]);
let c = a.sum_rows();
assert_eq!(*c.data(), vec![4.0, 6.0]);Sourcefn sum_cols(&self) -> Vector<T>
fn sum_cols(&self) -> Vector<T>
The sum of the columns of the matrix.
Returns a Vector equal to the sums of elements over the matrices columns.
Note that the resulting vector is identical to the sums of elements along each row of the matrix.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(2,2,vec![1.0,2.0,3.0,4.0]);
let c = a.sum_cols();
assert_eq!(*c.data(), vec![3.0, 7.0]);Sourcefn sum(&self) -> T
fn sum(&self) -> T
The sum of all elements in the matrix
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(2,2,vec![1.0,2.0,3.0,4.0]);
let c = a.sum();
assert_eq!(c, 10.0);Sourcefn into_matrix(self) -> Matrix<T>where
T: Copy,
fn into_matrix(self) -> Matrix<T>where
T: Copy,
Convert the matrix struct into a owned Matrix.
Sourcefn select_rows<'a, I>(&self, rows: I) -> Matrix<T>where
T: Copy,
I: IntoIterator<Item = &'a usize>,
<I as IntoIterator>::IntoIter: ExactSizeIterator + Clone,
fn select_rows<'a, I>(&self, rows: I) -> Matrix<T>where
T: Copy,
I: IntoIterator<Item = &'a usize>,
<I as IntoIterator>::IntoIter: ExactSizeIterator + Clone,
Select rows from matrix
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::<f64>::ones(3,3);
let b = &a.select_rows(&[2]);
assert_eq!(b.rows(), 1);
assert_eq!(b.cols(), 3);
let c = &a.select_rows(&[1,2]);
assert_eq!(c.rows(), 2);
assert_eq!(c.cols(), 3);§Panics
- Panics if row indices exceed the matrix dimensions.
Sourcefn select_cols<'a, I>(&self, cols: I) -> Matrix<T>where
T: Copy,
I: IntoIterator<Item = &'a usize>,
<I as IntoIterator>::IntoIter: ExactSizeIterator + Clone,
fn select_cols<'a, I>(&self, cols: I) -> Matrix<T>where
T: Copy,
I: IntoIterator<Item = &'a usize>,
<I as IntoIterator>::IntoIter: ExactSizeIterator + Clone,
Select columns from matrix
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::<f64>::ones(3,3);
let b = &a.select_cols(&[2]);
assert_eq!(b.rows(), 3);
assert_eq!(b.cols(), 1);
let c = &a.select_cols(&[1,2]);
assert_eq!(c.rows(), 3);
assert_eq!(c.cols(), 2);§Panics
- Panics if column indices exceed the matrix dimensions.
Sourcefn elemul(&self, m: &Self) -> Matrix<T>
fn elemul(&self, m: &Self) -> Matrix<T>
The elementwise product of two matrices.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(2,2,vec![1.0,2.0,3.0,4.0]);
let b = Matrix::new(2,2,vec![1.0,2.0,3.0,4.0]);
let c = &a.elemul(&b);
assert_eq!(*c.data(), vec![1.0, 4.0, 9.0, 16.0]);§Panics
- The matrices have different row counts.
- The matrices have different column counts.
Sourcefn elediv(&self, m: &Self) -> Matrix<T>
fn elediv(&self, m: &Self) -> Matrix<T>
The elementwise division of two matrices.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(2,2,vec![1.0,2.0,3.0,4.0]);
let b = Matrix::new(2,2,vec![1.0,2.0,3.0,4.0]);
let c = &a.elediv(&b);
assert_eq!(*c.data(), vec![1.0; 4]);§Panics
- The matrices have different row counts.
- The matrices have different column counts.
Sourcefn select(&self, rows: &[usize], cols: &[usize]) -> Matrix<T>where
T: Copy,
fn select(&self, rows: &[usize], cols: &[usize]) -> Matrix<T>where
T: Copy,
Select block matrix from matrix
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::<f64>::identity(3);
let b = &a.select(&[0,1], &[1,2]);
// We get the 2x2 block matrix in the upper right corner.
assert_eq!(b.rows(), 2);
assert_eq!(b.cols(), 2);
// Prints [0,0,1,0]
println!("{:?}", b.data());§Panics
- Panics if row or column indices exceed the matrix dimensions.
Sourcefn hcat<S>(&self, m: &S) -> Matrix<T>where
T: Copy,
S: BaseMatrix<T>,
fn hcat<S>(&self, m: &S) -> Matrix<T>where
T: Copy,
S: BaseMatrix<T>,
Horizontally concatenates two matrices. With self on the left.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(3,2, vec![1.0,2.0,3.0,4.0,5.0,6.0]);
let b = Matrix::new(3,1, vec![4.0,5.0,6.0]);
let c = &a.hcat(&b);
assert_eq!(c.cols(), a.cols() + b.cols());
assert_eq!(c[[1, 2]], 5.0);§Panics
- Self and m have different row counts.
Sourcefn vcat<S>(&self, m: &S) -> Matrix<T>where
T: Copy,
S: BaseMatrix<T>,
fn vcat<S>(&self, m: &S) -> Matrix<T>where
T: Copy,
S: BaseMatrix<T>,
Vertically concatenates two matrices. With self on top.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(2,3, vec![1.0,2.0,3.0,4.0,5.0,6.0]);
let b = Matrix::new(1,3, vec![4.0,5.0,6.0]);
let c = &a.vcat(&b);
assert_eq!(c.rows(), a.rows() + b.rows());
assert_eq!(c[[2, 2]], 6.0);§Panics
- Self and m have different column counts.
Sourcefn diag(&self) -> Vector<T>where
T: Copy,
fn diag(&self) -> Vector<T>where
T: Copy,
Extract the diagonal of the matrix
Examples
use rulinalg::vector::Vector;
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(3,3,vec![1,2,3,4,5,6,7,8,9]);
let b = Matrix::new(3,2,vec![1,2,3,4,5,6]);
let c = Matrix::new(2,3,vec![1,2,3,4,5,6]);
let d = &a.diag(); // 1,5,9
let e = &b.diag(); // 1,4
let f = &c.diag(); // 1,5
assert_eq!(*d.data(), vec![1,5,9]);
assert_eq!(*e.data(), vec![1,4]);
assert_eq!(*f.data(), vec![1,5]);Sourcefn transpose(&self) -> Matrix<T>where
T: Copy,
fn transpose(&self) -> Matrix<T>where
T: Copy,
Tranposes the given matrix
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let mat = Matrix::new(2,3, vec![1.0,2.0,3.0,4.0,5.0,6.0]);
let mt = mat.transpose();Sourcefn is_diag(&self) -> bool
fn is_diag(&self) -> bool
Checks if matrix is diagonal.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
let a = Matrix::new(2,2, vec![1.0,0.0,0.0,1.0]);
let a_diag = a.is_diag();
assert_eq!(a_diag, true);
let b = Matrix::new(2,2, vec![1.0,0.0,1.0,0.0]);
let b_diag = b.is_diag();
assert_eq!(b_diag, false);Sourcefn solve_u_triangular(&self, y: Vector<T>) -> Result<Vector<T>, Error>
fn solve_u_triangular(&self, y: Vector<T>) -> Result<Vector<T>, Error>
Solves an upper triangular linear system.
Given a matrix A and a vector b, this function returns the
solution of the upper triangular system Ux = b, where U is
the upper triangular part of A.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
use rulinalg::vector::Vector;
use std::f32;
let u = Matrix::new(2,2, vec![1.0, 2.0, 0.0, 1.0]);
let y = Vector::new(vec![3.0, 1.0]);
let x = u.solve_u_triangular(y).expect("A solution should exist!");
assert!((x[0] - 1.0) < f32::EPSILON);
assert!((x[1] - 1.0) < f32::EPSILON);§Panics
- Vector size and matrix column count are not equal.
§Failures
- There is no valid solution to the system (matrix is singular).
- The matrix is empty.
Sourcefn solve_l_triangular(&self, y: Vector<T>) -> Result<Vector<T>, Error>
fn solve_l_triangular(&self, y: Vector<T>) -> Result<Vector<T>, Error>
Solves a lower triangular linear system.
Given a matrix A and a vector b, this function returns the
solution of the lower triangular system Lx = b, where L is
the lower triangular part of A.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix};
use rulinalg::vector::Vector;
use std::f32;
let l = Matrix::new(2,2, vec![1.0, 0.0, 2.0, 1.0]);
let y = Vector::new(vec![1.0, 3.0]);
let x = l.solve_l_triangular(y).expect("A solution should exist!");
println!("{:?}", x);
assert!((x[0] - 1.0) < f32::EPSILON);
assert!((x[1] - 1.0) < f32::EPSILON);§Panics
- Vector size and matrix column count are not equal.
§Failures
- There is no valid solution to the system (matrix is singular).
- The matrix is empty.
Sourcefn split_at(
&self,
mid: usize,
axis: Axes,
) -> (MatrixSlice<'_, T>, MatrixSlice<'_, T>)
fn split_at( &self, mid: usize, axis: Axes, ) -> (MatrixSlice<'_, T>, MatrixSlice<'_, T>)
Split the matrix at the specified axis returning two MatrixSlices.
§Examples
use rulinalg::matrix::{Axes, Matrix, BaseMatrix};
let a = Matrix::new(3,3, vec![2.0; 9]);
let (b,c) = a.split_at(1, Axes::Row);Sourcefn sub_slice<'a>(
&self,
start: [usize; 2],
rows: usize,
cols: usize,
) -> MatrixSlice<'a, T>where
T: 'a,
fn sub_slice<'a>(
&self,
start: [usize; 2],
rows: usize,
cols: usize,
) -> MatrixSlice<'a, T>where
T: 'a,
Produce a MatrixSlice from an existing matrix.
§Examples
use rulinalg::matrix::{Matrix, BaseMatrix, MatrixSlice};
let a = Matrix::new(3,3, (0..9).collect::<Vec<usize>>());
let slice = MatrixSlice::from_matrix(&a, [1,1], 2, 2);
let new_slice = slice.sub_slice([0,0], 1, 1);Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.