diff options
Diffstat (limited to 'src/types/matrix.rs')
-rw-r--r-- | src/types/matrix.rs | 23 |
1 files changed, 20 insertions, 3 deletions
diff --git a/src/types/matrix.rs b/src/types/matrix.rs index 935d0dd..d3b4333 100644 --- a/src/types/matrix.rs +++ b/src/types/matrix.rs @@ -1,4 +1,4 @@ -use std::{fmt::Display, str::FromStr}; +use std::{fmt::Display, ops::Add, str::FromStr}; /// Matrix pub struct Matrix { pub nrows: usize, @@ -27,11 +27,28 @@ impl Display for Matrix { write!(f, "{}", builder) } } +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) { panic!("Cannot add two matrices with different dimensions"); } + let mut x = Matrix { + nrows: self.nrows, + ncols: self.ncols, + data: self.data.clone(), + }; + for (i, r) in rhs.data.iter().enumerate() { + for (j, n) in r.iter().enumerate() { + x.data[i][j] += n; + } + } + x + } +} impl Matrix { pub fn new(data: Vec<Vec<i32>>) -> Matrix { Matrix { - nrows: data[0].len(), - ncols: data.len(), + nrows: data.len(), + ncols: data[0].len(), data, } } |