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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
|
//! Matrix struct and relevant implementations.
//!
//! Example usage - addition of two matrices:
//! ```
//! use matrix::Matrix;
//! use std::str::FromStr;
//! let m1 = Matrix::from_str("1,2\n3,4").expect("Expect parse correct");
//! let m2 = Matrix::from_str("1,1\n1,1").expect("Expect parse correct");
//! let m_add = &m1 + &m2;
//! println!("m1 + m2 =\n{}", m_add);
//! ```
//! TODO:: Create matrix multiplication method
use core::ops::AddAssign;
use crate::error::{MatrixSetValueError, ParseMatrixError};
use std::{
fmt::Display,
ops::{Add, Mul, Sub},
str::FromStr,
};
#[derive(Debug, PartialEq)]
pub struct Matrix {
/// Number of rows in matrix.
pub nrows: usize,
/// Number of columns in matrix.
pub ncols: usize,
/// Data stored in the matrix, you should not access this directly
data: Vec<Vec<f32>>,
}
pub trait MatrixMath {
fn inverse(&self) -> Option<Matrix> {
let det_m = self.determinant();
if det_m == 0.0 {
return None;
}
Some((1.0 / det_m) * &self.adjoint())
}
/// Finds the matrix of cofactors for any N-by-N matrix
fn cofactor(&self) -> Matrix {
todo!();
}
/// Finds the matrix of minors for any N-by-N matrix.
fn minor(&self) -> Matrix {
todo!();
}
/// Finds the determinant of any N-by-N matrix.
fn determinant(&self) -> f32 {
todo!();
}
/// Finds the transpose of any matrix.
fn transpose(&self) -> Matrix {
todo!();
}
/// Finds the adjoint matrix (transpose of cofactors) for any N-by-N matrix.
fn adjoint(&self) -> Matrix {
self.cofactor().transpose()
}
}
impl MatrixMath for Matrix {
fn cofactor(&self) -> Matrix {
let mut d: Vec<Vec<f32>> = Vec::new();
for (i, r) in self.data.iter().enumerate() {
let mut nr: Vec<f32> = Vec::new();
for (j, v) in r.iter().enumerate() {
let count = self.ncols * i + j;
let nv = if count % 2 == 0 { -*v } else { *v };
nr.push(nv);
}
d.push(nr);
}
Matrix::new(d)
}
fn minor(&self) -> Matrix {
let mut d: Vec<Vec<f32>> = Vec::new();
for (i, r) in self.data.iter().enumerate() {
let mut nr: Vec<f32> = Vec::new();
for (j, v) in r.iter().enumerate() {
let count = self.ncols * i + j;
let nv = if count % 2 == 0 { -*v } else { *v };
nr.push(nv * self.splice(j, i).determinant());
}
d.push(nr);
}
Matrix::new(d)
}
/// Evaluates any N-by-N matrix.
///
/// This function panics if the matrix is not square!
fn determinant(&self) -> f32 {
if !self.is_square() {
panic!()
};
if self.nrows == 2 && self.ncols == 2 {
return self.data[0][0] * self.data[1][1] - self.data[0][1] * self.data[1][0];
}
let mut tmp: f32 = 0.0;
for (i, n) in self.data[0].iter().enumerate() {
let mult = if i % 2 == 0 { -*n } else { *n };
let eval = self.splice(i, 0).determinant();
tmp = tmp + mult * f32::from(eval);
}
tmp.into()
}
/// Evaluates the tranpose of the matrix.
///
/// Each row becomes a column, each column becomes a row.
fn transpose(&self) -> Matrix {
let mut new_data = Vec::<Vec<f32>>::new();
for i in 0..self.nrows {
let mut new_row = Vec::<f32>::new();
for j in 0..self.ncols {
new_row.push(self.data[j][i]);
}
new_data.push(new_row);
}
Matrix {
nrows: self.ncols,
ncols: self.nrows,
data: new_data,
}
}
}
impl Matrix {
/// Matrix initialiser function.
///
/// Accepts a new array of data as a list of rows.
///
/// TODOs
/// - Add row length check
pub fn new(data: Vec<Vec<f32>>) -> Matrix {
let mut d: Vec<Vec<f32>> = Vec::new();
for r in &data {
let mut nr = vec![];
for x in r {
nr.push(*x);
}
d.push(nr);
}
Matrix {
nrows: data.len(),
ncols: data[0].len(),
data: d,
}
}
/// Query one element at selected position.
///
/// Returns `None` if index is out of bounds.
pub fn get(&self, row_index: usize, column_index: usize) -> Option<f32> {
let r = self.data.get(row_index)?;
let n = r.get(column_index)?;
Some(*n)
}
/// Update one element at selected position.
///
/// Returns `Err()` if index is out of bounds.
pub fn set(
&mut self,
row_index: usize,
column_index: usize,
new_data: f32,
) -> Result<(), MatrixSetValueError> {
self.data[row_index][column_index] = new_data;
Ok(())
}
/// Checks if this is a square matrix.
pub fn is_square(&self) -> bool {
self.nrows == self.ncols
}
fn splice(&self, at_index: usize, at_row: usize) -> Matrix {
let mut data: Vec<Vec<f32>> = Vec::new();
for i in 0..self.data.len() {
if i == at_row {
continue;
}
let mut r: Vec<f32> = Vec::new();
for j in 0..self.data[i].len() {
if j == at_index {
continue;
}
r.push(self.data[i][j]);
}
data.push(r);
}
Matrix::new(data)
}
}
impl FromStr for Matrix {
type Err = ParseMatrixError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut d: Vec<Vec<f32>> = Vec::new();
let rows_iter = s.split('\n');
for txt in rows_iter {
let mut r: Vec<f32> = Vec::new();
for ch in txt.split(',') {
let parsed = match f32::from_str(ch) {
Ok(n) => Ok(n),
Err(_e) => Err(ParseMatrixError),
};
r.push(parsed?);
}
d.push(r);
}
Ok(Matrix::new(d))
}
}
impl Display for Matrix {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut builder = String::new();
for (i, r) in self.data.iter().enumerate() {
let mut row_str = if i == 0 || i == self.nrows - 1 {
"+".to_string()
} else {
"|".to_string()
};
for (j, n) in r.iter().enumerate() {
row_str += &format!("{}{}", n, if j == self.ncols - 1 { "" } else { "," });
}
row_str += if i == 0 || i == self.nrows - 1 {
"+\n"
} else {
"|\n"
};
builder += &row_str;
}
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<'a, 'b> Sub<&'b Matrix> for &'a Matrix {
type Output = Matrix;
fn sub(self, rhs: &'b Matrix) -> Self::Output {
todo!()
}
}
impl<'a> Mul<&'a Matrix> for f32 {
type Output = Matrix;
fn mul(self, rhs: &'a Matrix) -> Self::Output {
let mut d: Vec<Vec<f32>> = Vec::new();
for r in &rhs.data {
let mut nr: Vec<f32> = Vec::new();
for v in r {
nr.push(self * v);
}
d.push(nr);
}
Matrix::new(d)
}
}
impl<'a, 'b> Mul<&'b Matrix> for &'a Matrix {
type Output = Matrix;
fn mul(self, rhs: &'b Matrix) -> Self::Output {
fn reduce(lhs: &Matrix, rhs: &Matrix, at_r: usize, at_c: usize) -> f32 {
let mut tmp = 0.0;
for i in 0..lhs.ncols {
tmp += lhs.get(at_r, i).unwrap() * rhs.get(i, at_c).unwrap();
}
tmp
}
let mut d: Vec<Vec<f32>> = Vec::new();
if self.ncols != rhs.nrows {
println!("LHS: \n{}RHS: \n{}", self, rhs);
println!("LHS nrows: {} ;; RHS ncols: {}", self.nrows, rhs.ncols);
panic!()
}
for i in 0..self.nrows {
let mut r: Vec<f32> = Vec::new();
for j in 0..rhs.ncols {
r.push(reduce(self, rhs, i, j));
}
d.push(r);
}
Matrix::new(d)
}
}
impl From<Vec<f32>> for Matrix {
fn from(value: Vec<f32>) -> Self {
Matrix {
nrows: value.len(),
ncols: 1,
data: value.iter().map(|v| vec![*v]).collect(),
}
}
}
|