rust_linear_algebra/matrix/
mod.rs

1pub mod determinant;
2mod gaussian_elemination;
3pub mod identity;
4pub mod inverse;
5pub mod ops;
6pub mod rank;
7pub mod row_echelon;
8pub mod trace;
9pub mod transpose;
10
11pub use identity::*;
12pub use ops::*;
13
14use std::cmp::PartialEq;
15use std::fmt::Debug;
16use std::slice::{Iter, IterMut};
17use std::usize;
18
19#[derive(Debug, Clone)]
20pub struct Matrix<K> {
21    pub elements: Vec<Vec<K>>,
22}
23
24impl<K> From<Vec<Vec<K>>> for Matrix<K> {
25    fn from(elements: Vec<Vec<K>>) -> Self {
26        Matrix { elements }
27    }
28}
29
30impl<K, const ROWS: usize, const COLS: usize> From<[[K; COLS]; ROWS]> for Matrix<K>
31where
32    K: Clone,
33{
34    fn from(array: [[K; COLS]; ROWS]) -> Self {
35        let elements = array.iter().map(|row| row.to_vec()).collect();
36        Matrix { elements }
37    }
38}
39
40impl<K: Default + Clone> Matrix<K> {
41    pub fn new(rows: usize, cols: usize) -> Self {
42        let elements = vec![vec![K::default(); cols]; rows];
43        Matrix { elements }
44    }
45}
46
47impl<K> Matrix<K> {
48    pub fn iter(&self) -> Iter<Vec<K>> {
49        self.elements.iter()
50    }
51    pub fn iter_mut(&mut self) -> IterMut<Vec<K>> {
52        self.elements.iter_mut()
53    }
54    pub fn rows(&self) -> usize {
55        self.elements.len()
56    }
57    pub fn cols(&self) -> usize {
58        self.elements[0].len()
59    }
60}
61
62impl<K> PartialEq for Matrix<K>
63where
64    Vec<K>: PartialEq,
65    K: PartialEq,
66{
67    fn eq(&self, other: &Self) -> bool {
68        self.iter().zip(other.iter()).all(|(a, b)| a == b)
69    }
70    fn ne(&self, other: &Self) -> bool {
71        !self.eq(other)
72    }
73}