mirror of
https://github.com/SinTan1729/matrix-basic.git
synced 2024-12-25 21:48:35 -06:00
new: Implement Sub trait
This commit is contained in:
parent
dfc15a399c
commit
c14f13b148
2 changed files with 22 additions and 3 deletions
|
@ -13,11 +13,13 @@ mod tests {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn add_test() {
|
fn add_sub_test() {
|
||||||
let a = Matrix::from(vec![vec![1, 2, 3], vec![0, 1, 2]]).unwrap();
|
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 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();
|
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]
|
#[test]
|
||||||
|
|
|
@ -5,7 +5,7 @@ use std::{
|
||||||
result::Result,
|
result::Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(PartialEq, Debug)]
|
#[derive(PartialEq, Debug, Clone)]
|
||||||
pub struct Matrix<T: Mul + Add + Sub> {
|
pub struct Matrix<T: Mul + Add + Sub> {
|
||||||
entries: Vec<Vec<T>>,
|
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.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue