Skip to content

Instantly share code, notes, and snippets.

@lamalex
Created May 22, 2020 23:48
Show Gist options
  • Select an option

  • Save lamalex/2667a2584fdbdce89356972e7621a515 to your computer and use it in GitHub Desktop.

Select an option

Save lamalex/2667a2584fdbdce89356972e7621a515 to your computer and use it in GitHub Desktop.

Revisions

  1. Alex Launi created this gist May 22, 2020.
    58 changes: 58 additions & 0 deletions lib.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    pub mod matrix {
    use num_traits::Num;
    pub struct Matrix<T> {
    pub rows: usize,
    pub cols: usize,
    data: Vec<T>,
    }

    impl<T> Matrix<T>
    where
    T: Num + Copy,
    {
    pub fn new(rows: usize, cols: usize) -> Self {
    assert!(rows > 0 && cols > 0);
    Matrix {
    rows: rows,
    cols: cols,
    data: vec![T::zero(); rows * cols],
    }
    }

    pub fn from(v: Vec<Vec<T>>) -> Self {
    let mut a = Matrix::<T>::new(v.len(), v[0].len());
    for (i, e) in v.iter().flatten().enumerate() {
    a.data[i] = *e;
    }
    a
    }

    pub fn transpose(self) -> Self {
    self
    }
    }

    #[macro_export]
    macro_rules! mat {
    ($([$($x:expr),* $(,)*]),+ $(,)*) => {{
    crate::matrix::Matrix::from(vec![$([$($x,)*].to_vec(),)*])
    }}
    }

    #[cfg(test)]
    mod tests {
    use super::*;
    #[test]
    #[should_panic]
    fn test_panic_on_0_size() {
    let a = Matrix::<u8>::new(0, 0);
    let b = Matrix::<u8>::new(1, 0);
    let a = Matrix::<u8>::new(0, 1);
    }

    fn test_create_matrix_macro() {
    let a = mat![[1, 2], [3, 4]];
    assert_eq!(a.data, [1, 2, 3, 4]);
    }
    }
    }
    9 changes: 9 additions & 0 deletions main.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    #[macro_use]
    use matrixsolver;
    use matrixsolver::matrix::*;

    fn main() {
    println!("oh brother");
    let a = mat![[1, 2], [3, 4]];
    println!("{} {}", a.rows, a.cols);
    }