rust_linear_algebra/matrix/ops/
add.rs1use super::super::Matrix;
2use std::ops::Add;
3
4impl<K> Add for Matrix<K>
5where
6 K: Add<Output = K> + Copy + Default,
7{
8 type Output = Matrix<K>;
9
10 fn add(self, rhs: Self) -> Self::Output {
11 if self.rows() != rhs.rows() || self.cols() != rhs.cols() {
12 panic!("Matrices must have the same dimensions");
13 }
14
15 let mut elements = vec![vec![K::default(); self.cols()]; self.rows()];
16
17 for i in 0..self.rows() {
18 for j in 0..self.cols() {
19 elements[i][j] = self.elements[i][j] + rhs.elements[i][j];
20 }
21 }
22
23 Matrix { elements }
24 }
25}
26
27impl<K> Matrix<K>
28where
29 K: Add<Output = K> + Copy,
30{
31 pub fn add(&mut self, m: Matrix<K>) {
32 if self.rows() != m.rows() || self.cols() != m.cols() {
33 panic!("Matrices must have the same dimensions");
34 }
35
36 self.iter_mut()
37 .zip(m.iter())
38 .for_each(|(row_self, row_other)| {
39 row_self
40 .iter_mut()
41 .zip(row_other.iter())
42 .for_each(|(a, b)| *a = *a + *b)
43 });
44 }
45}