new: Implement Sub trait

This commit is contained in:
Sayantan Santra 2023-05-24 23:39:46 -05:00
parent dfc15a399c
commit c14f13b148
Signed by: SinTan1729
GPG key ID: EB3E68BFBA25C85F
2 changed files with 22 additions and 3 deletions

View file

@ -13,11 +13,13 @@ mod tests {
}
#[test]
fn add_test() {
fn add_sub_test() {
let a = Matrix::from(vec![vec![1, 2, 3], vec![0, 1, 2]]).unwrap();
let b = Matrix::from(vec![vec![0, 0, 1], vec![2, 1, 3]]).unwrap();
let c = Matrix::from(vec![vec![1, 2, 4], vec![2, 2, 5]]).unwrap();
assert_eq!(a + b, c);
let d = Matrix::from(vec![vec![1, 2, 2], vec![-2, 0, -1]]).unwrap();
assert_eq!(a.clone() + b.clone(), c);
assert_eq!(a - b, d);
}
#[test]

View file

@ -5,7 +5,7 @@ use std::{
result::Result,
};
#[derive(PartialEq, Debug)]
#[derive(PartialEq, Debug, Clone)]
pub struct Matrix<T: Mul + Add + Sub> {
entries: Vec<Vec<T>>,
}
@ -162,3 +162,20 @@ impl<T: Add<Output = T> + Sub + Mul + Copy + Zero> Add for Matrix<T> {
}
}
}
impl<T: Add + Sub<Output = T> + Mul + Copy + Zero> Sub for Matrix<T> {
type Output = Self;
fn sub(self, other: Self) -> Self {
if self.height() == other.height() && self.width() == other.width() {
let mut out = self.entries.clone();
for (i, row) in self.rows().iter().enumerate() {
for (j, entry) in other.rows()[i].iter().enumerate() {
out[i][j] = row[j] - *entry;
}
}
Matrix { entries: out }
} else {
panic!("Both matrices must be of same dimensions.");
}
}
}