diff options
Diffstat (limited to 'src/matrix.rs')
-rw-r--r-- | src/matrix.rs | 28 |
1 files changed, 25 insertions, 3 deletions
diff --git a/src/matrix.rs b/src/matrix.rs index c324c36..a81fcf0 100644 --- a/src/matrix.rs +++ b/src/matrix.rs @@ -10,8 +10,8 @@ //! println!("m1 + m2 =\n{}", m_add); //! ``` //! TODO:: Create matrix multiplication method -use core::ops::AddAssign; use crate::error::{MatrixSetValueError, ParseMatrixError}; +use core::ops::AddAssign; use std::{ fmt::Display, ops::{Add, Mul, Sub}, @@ -146,6 +146,9 @@ impl Matrix { data: d, } } + pub fn same_dimensions(&self, other: &Matrix) -> bool { + self.nrows == other.nrows && self.ncols == other.ncols + } /// Query one element at selected position. /// /// Returns `None` if index is out of bounds. @@ -172,6 +175,21 @@ impl Matrix { pub fn is_square(&self) -> bool { self.nrows == self.ncols } + pub fn permute_op(&self, op: fn(f32) -> f32) -> Matrix { + let mut i = 0; + let mut j = 0; + let mut rs: Vec<Vec<f32>> = Vec::new(); + while i < self.nrows { + let mut r: Vec<f32> = Vec::new(); + while j < self.ncols { + r.push(op(self.get(i, j).unwrap())); + j += 1; + } + rs.push(r); + i += 1; + } + Matrix::new(rs) + } fn splice(&self, at_index: usize, at_row: usize) -> Matrix { let mut data: Vec<Vec<f32>> = Vec::new(); for i in 0..self.data.len() { @@ -235,7 +253,7 @@ impl Display for Matrix { impl<'a, 'b> Add<&'b Matrix> for &'a Matrix { type Output = Matrix; fn add(self, rhs: &'b Matrix) -> Self::Output { - if (self.nrows != rhs.nrows) || (self.ncols != rhs.ncols) { + if !self.same_dimensions(rhs) { panic!("Cannot add two matrices with different dimensions"); } let mut x = Matrix { @@ -254,7 +272,11 @@ impl<'a, 'b> Add<&'b Matrix> for &'a Matrix { impl<'a, 'b> Sub<&'b Matrix> for &'a Matrix { type Output = Matrix; fn sub(self, rhs: &'b Matrix) -> Self::Output { - todo!() + if !self.same_dimensions(rhs) { + panic!("Cannot subtract two matrices with different dimensions"); + } + let neg = rhs.permute_op(|x| -x); + self - &neg } } impl<'a> Mul<&'a Matrix> for f32 { |