1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use std::default::Default;
use std::ops::{Add, AddAssign, Div, Mul};
mod tests;
pub struct Matrix<T> {
r: usize,
c: usize,
buf: Vec<T>,
}
impl<T> Matrix<T>
where
T: Copy + Add<Output = T> + Div<Output = T>,
{
pub fn new(r: usize, c: usize, v: Vec<T>) -> Matrix<T> {
assert_eq!(r * c, v.len(), "Matrix dimensions and data size differ");
Matrix { r, c, buf: v }
}
pub fn from_vec(r: usize, c: usize, v: &Vec<T>) -> Matrix<T> {
assert_eq!(r * c, v.len(), "Matrix dimensions and data size differ");
Matrix {
r,
c,
buf: v.clone(),
}
}
pub fn rows(&self) -> usize {
self.r
}
pub fn cols(&self) -> usize {
self.c
}
pub fn at(&self, r: usize, c: usize) -> &T {
assert!(r < self.r && c < self.c, "Out of bounds");
&self.buf[r * self.c + c]
}
pub fn at_mut(&mut self, r: usize, c: usize) -> &mut T {
&mut self.buf[r * self.c + c]
}
pub fn data(&self) -> &Vec<T> {
&self.buf
}
pub fn map<U, F>(&self, f: F) -> Matrix<U>
where
U: Copy + Add<Output = U> + Div<Output = U>,
F: Fn(&T) -> U,
{
let new_v = self.buf.iter().map(f).collect();
Matrix::new(self.r, self.c, new_v)
}
pub fn diagonal(&self) -> Vec<T> {
self.check_square();
self.buf
.iter()
.zip(0..self.buf.len())
.filter(|(_, i)| i % self.c == i / self.r)
.map(|(&elem, _)| elem)
.collect()
}
fn check_square(&self) {
assert_eq!(self.r, self.c, "Matrix is not square");
}
}
impl<'a, T> Add<&'a Matrix<T>> for &'a Matrix<T>
where
T: Copy + Add<Output = T> + Div<Output = T>,
{
type Output = Matrix<T>;
fn add(self, other: Self) -> Self::Output {
assert!(
self.r == other.rows() && self.c == other.cols(),
"Matrices are not of the same size"
);
let new_v = self
.buf
.iter()
.zip(other.data())
.map(|(&x, &y)| x + y)
.collect();
Matrix::new(self.r, self.c, new_v)
}
}
impl<'a, T> Mul<&'a Matrix<T>> for &'a Matrix<T>
where
T: Copy + Add<Output = T> + AddAssign<T> + Mul<Output = T> + Div<Output = T> + Default,
{
type Output = Matrix<T>;
fn mul(self, other: Self) -> Self::Output {
assert_eq!(self.c, other.r);
let mut v: Vec<T> = vec![Default::default(); self.r * other.c];
for i in 0..self.r {
for j in 0..other.c {
for k in 0..self.c {
v[i * self.r + j] += self.buf[i * self.c + k] * other.buf[k * other.c + j];
}
}
}
Matrix::new(self.r, other.c, v)
}
}