forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 1
/
matrix_ops.rs
569 lines (475 loc) · 13.1 KB
/
matrix_ops.rs
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// Basic matrix operations using a Matrix type with internally uses
// a vector representation to store matrix elements.
// Generic using the MatrixElement trait, which can be implemented with
// the matrix_element_type_def macro.
// Wikipedia reference: https://www.wikiwand.com/en/Matrix_(mathematics)
use std::ops::{Add, AddAssign, Index, IndexMut, Mul, Sub};
// Define macro to build a matrix idiomatically
#[macro_export]
macro_rules! matrix {
[$([$($x:expr),* $(,)*]),* $(,)*] => {{
Matrix::from(vec![$(vec![$($x,)*],)*])
}};
}
// Define a trait "alias" for suitable matrix elements
pub trait MatrixElement:
Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + AddAssign + Copy + From<u8>
{
}
// Define a macro to implement the MatrixElement trait for desired types
#[macro_export]
macro_rules! matrix_element_type_def {
($T: ty) => {
// Implement trait for type
impl MatrixElement for $T {}
// Defining left-hand multiplication in this form
// prevents errors for uncovered types
impl Mul<&Matrix<$T>> for $T {
type Output = Matrix<$T>;
fn mul(self, rhs: &Matrix<$T>) -> Self::Output {
rhs * self
}
}
};
($T: ty, $($Ti: ty),+) => {
// Decompose type definitions recursively
matrix_element_type_def!($T);
matrix_element_type_def!($($Ti),+);
};
}
matrix_element_type_def!(i16, i32, i64, i128, u8, u16, u32, u128, f32, f64);
#[derive(PartialEq, Eq, Debug)]
pub struct Matrix<T: MatrixElement> {
data: Vec<T>,
rows: usize,
cols: usize,
}
impl<T: MatrixElement> Matrix<T> {
pub fn new(data: Vec<T>, rows: usize, cols: usize) -> Self {
// Build a matrix from the internal vector representation
if data.len() != rows * cols {
panic!("Inconsistent data and dimensions combination for matrix")
}
Matrix { data, rows, cols }
}
pub fn zero(rows: usize, cols: usize) -> Self {
// Build a matrix of zeros
Matrix {
data: vec![0.into(); rows * cols],
rows,
cols,
}
}
pub fn identity(len: usize) -> Self {
// Build an identity matrix
let mut identity = Matrix::zero(len, len);
// Diagonal of ones
for i in 0..len {
identity[[i, i]] = 1.into();
}
identity
}
pub fn transpose(&self) -> Self {
// Transpose a matrix of any size
let mut result = Matrix::zero(self.cols, self.rows);
for i in 0..self.rows {
for j in 0..self.cols {
result[[i, j]] = self[[j, i]];
}
}
result
}
}
impl<T: MatrixElement> Index<[usize; 2]> for Matrix<T> {
type Output = T;
fn index(&self, index: [usize; 2]) -> &Self::Output {
let [i, j] = index;
if i >= self.rows || j >= self.cols {
panic!("Matrix index out of bounds");
}
&self.data[(self.cols * i) + j]
}
}
impl<T: MatrixElement> IndexMut<[usize; 2]> for Matrix<T> {
fn index_mut(&mut self, index: [usize; 2]) -> &mut Self::Output {
let [i, j] = index;
if i >= self.rows || j >= self.cols {
panic!("Matrix index out of bounds");
}
&mut self.data[(self.cols * i) + j]
}
}
impl<T: MatrixElement> Add<&Matrix<T>> for &Matrix<T> {
type Output = Matrix<T>;
fn add(self, rhs: &Matrix<T>) -> Self::Output {
// Add two matrices. They need to have identical dimensions.
if self.rows != rhs.rows || self.cols != rhs.cols {
panic!("Matrix dimensions do not match");
}
let mut result = Matrix::zero(self.rows, self.cols);
for i in 0..self.rows {
for j in 0..self.cols {
result[[i, j]] = self[[i, j]] + rhs[[i, j]];
}
}
result
}
}
impl<T: MatrixElement> Sub for &Matrix<T> {
type Output = Matrix<T>;
fn sub(self, rhs: Self) -> Self::Output {
// Subtract one matrix from another. They need to have identical dimensions.
if self.rows != rhs.rows || self.cols != rhs.cols {
panic!("Matrix dimensions do not match");
}
let mut result = Matrix::zero(self.rows, self.cols);
for i in 0..self.rows {
for j in 0..self.cols {
result[[i, j]] = self[[i, j]] - rhs[[i, j]];
}
}
result
}
}
impl<T: MatrixElement> Mul for &Matrix<T> {
type Output = Matrix<T>;
fn mul(self, rhs: Self) -> Self::Output {
// Multiply two matrices. The multiplier needs to have the same amount
// of columns as the multiplicand has rows.
if self.cols != rhs.rows {
panic!("Matrix dimensions do not match");
}
let mut result = Matrix::zero(self.rows, rhs.cols);
for i in 0..self.rows {
for j in 0..rhs.cols {
result[[i, j]] = {
let mut sum = 0.into();
for k in 0..self.cols {
sum += self[[i, k]] * rhs[[k, j]];
}
sum
};
}
}
result
}
}
impl<T: MatrixElement> Mul<T> for &Matrix<T> {
type Output = Matrix<T>;
fn mul(self, rhs: T) -> Self::Output {
// Multiply a matrix of any size with a scalar
let mut result = Matrix::zero(self.rows, self.cols);
for i in 0..self.rows {
for j in 0..self.cols {
result[[i, j]] = rhs * self[[i, j]];
}
}
result
}
}
impl<T: MatrixElement> From<Vec<Vec<T>>> for Matrix<T> {
fn from(v: Vec<Vec<T>>) -> Self {
let rows = v.len();
let cols = v.first().map_or(0, |row| row.len());
// Ensure consistent dimensions
for row in v.iter().skip(1) {
if row.len() != cols {
panic!("Invalid matrix dimensions. Columns must be consistent.");
}
}
if rows != 0 && cols == 0 {
panic!("Invalid matrix dimensions. Multiple empty rows");
}
let data = v.into_iter().flat_map(|row| row.into_iter()).collect();
Self::new(data, rows, cols)
}
}
#[cfg(test)]
// rustfmt skipped to prevent unformatting matrix definitions to a single line
#[rustfmt::skip]
mod tests {
use super::Matrix;
use std::panic;
const DELTA: f64 = 1e-3;
macro_rules! assert_f64_eq {
($a:expr, $b:expr) => {
assert_eq!($a.data.len(), $b.data.len());
if !$a
.data
.iter()
.zip($b.data.iter())
.all(|(x, y)| (*x as f64 - *y as f64).abs() < DELTA)
{
panic!();
}
};
}
#[test]
fn test_invalid_matrix() {
let result = panic::catch_unwind(|| matrix![
[1, 0, 0, 4],
[0, 1, 0],
[0, 0, 1],
]);
assert!(result.is_err());
}
#[test]
fn test_empty_matrix() {
let a: Matrix<i32> = matrix![];
let result = panic::catch_unwind(|| a[[0, 0]]);
assert!(result.is_err());
}
#[test]
fn test_zero_matrix() {
let a: Matrix<f64> = Matrix::zero(3, 5);
let z = matrix![
[0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0],
];
assert_f64_eq!(a, z);
}
#[test]
fn test_identity_matrix() {
let a: Matrix<f64> = Matrix::identity(5);
let id = matrix![
[1.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 1.0],
];
assert_f64_eq!(a, id);
}
#[test]
fn test_invalid_add() {
let a = matrix![
[1, 0, 1],
[0, 2, 0],
[5, 0, 1]
];
let err = matrix![
[1, 2],
[2, 4],
];
let result = panic::catch_unwind(|| &a + &err);
assert!(result.is_err());
}
#[test]
fn test_add_i32() {
let a = matrix![
[1, 0, 1],
[0, 2, 0],
[5, 0, 1]
];
let b = matrix![
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];
let add = matrix![
[2, 0, 1],
[0, 3, 0],
[5, 0, 2],
];
assert_eq!(&a + &b, add);
}
#[test]
fn test_add_f64() {
let a = matrix![
[1.0, 2.0, 1.0],
[3.0, 2.0, 0.0],
[5.0, 0.0, 1.0],
];
let b = matrix![
[1.0, 10.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
];
let add = matrix![
[2.0, 12.0, 1.0],
[3.0, 3.0, 0.0],
[5.0, 0.0, 2.0],
];
assert_f64_eq!(&a + &b, add);
}
#[test]
fn test_invalid_sub() {
let a = matrix![
[2, 3],
[10, 2],
];
let err = matrix![
[5, 6, 10],
[7, 2, 2],
[12, 0, 1],
];
let result = panic::catch_unwind(|| &a - &err);
assert!(result.is_err());
}
#[test]
fn test_subtract_i32() {
let a = matrix![
[1, 0, 1],
[0, 2, 0],
[5, 0, 1],
];
let b = matrix![
[1, 0, 0],
[0, 1, 3],
[0, 0, 1],
];
let sub = matrix![
[0, 0, 1],
[0, 1, -3],
[5, 0, 0],
];
assert_eq!(&a - &b, sub);
}
#[test]
fn test_subtract_f64() {
let a = matrix![
[7.0, 2.0, 1.0],
[0.0, 3.0, 2.0],
[5.3, 8.8, std::f64::consts::PI],
];
let b = matrix![
[1.0, 0.0, 5.0],
[-2.0, 1.0, 3.0],
[0.0, 2.2, std::f64::consts::PI],
];
let sub = matrix![
[6.0, 2.0, -4.0],
[2.0, 2.0, -1.0],
[5.3, 6.6, 0.0],
];
assert_f64_eq!(&a - &b, sub);
}
#[test]
fn test_invalid_mul() {
let a = matrix![
[1, 2, 3],
[4, 2, 6],
[3, 4, 1],
[2, 4, 8],
];
let err = matrix![
[1, 3, 3, 2],
[7, 6, 2, 1],
[3, 4, 2, 1],
[3, 4, 2, 1],
];
let result = panic::catch_unwind(|| &a * &err);
assert!(result.is_err());
}
#[test]
fn test_mul_i32() {
let a = matrix![
[1, 2, 3],
[4, 2, 6],
[3, 4, 1],
[2, 4, 8],
];
let b = matrix![
[1, 3, 3, 2],
[7, 6, 2, 1],
[3, 4, 2, 1],
];
let mul = matrix![
[24, 27, 13, 7],
[36, 48, 28, 16],
[34, 37, 19, 11],
[54, 62, 30, 16],
];
assert_eq!(&a * &b, mul);
}
#[test]
fn test_mul_f64() {
let a = matrix![
[5.5, 2.9, 1.13, 9.0],
[0.0, 3.0, 11.0, 17.2],
[5.3, 8.8, 2.76, 3.3],
];
let b = matrix![
[1.0, 0.3, 5.0],
[-2.0, 1.0, 3.0],
[-3.6, 1.5, 3.0],
[0.0, 2.2, 2.0],
];
let mul = matrix![
[-4.368, 26.045, 57.59],
[-45.6, 57.34, 76.4],
[-22.236, 21.79, 67.78],
];
assert_f64_eq!(&a * &b, mul);
}
#[test]
fn test_transpose_i32() {
let a = matrix![
[1, 0, 1],
[0, 2, 0],
[5, 0, 1],
];
let t = matrix![
[1, 0, 5],
[0, 2, 0],
[1, 0, 1],
];
assert_eq!(a.transpose(), t);
}
#[test]
fn test_transpose_f64() {
let a = matrix![
[3.0, 4.0, 2.0],
[0.0, 1.0, 3.0],
[3.0, 1.0, 1.0],
];
let t = matrix![
[3.0, 0.0, 3.0],
[4.0, 1.0, 1.0],
[2.0, 3.0, 1.0],
];
assert_eq!(a.transpose(), t);
}
#[test]
fn test_matrix_scalar_zero_mul() {
let a = matrix![
[3, 2, 2],
[0, 2, 0],
[5, 4, 1],
];
let scalar = 0;
let scalar_mul = Matrix::zero(3, 3);
assert_eq!(scalar * &a, scalar_mul);
}
#[test]
fn test_matrix_scalar_mul_i32() {
let a = matrix![
[3, 2, 2],
[0, 2, 0],
[5, 4, 1],
];
let scalar = 3;
let scalar_mul = matrix![
[9, 6, 6],
[0, 6, 0],
[15, 12, 3],
];
assert_eq!(scalar * &a, scalar_mul);
}
#[test]
fn test_matrix_scalar_mul_f64() {
let a = matrix![
[3.2, 5.5, 9.2],
[1.1, 0.0, 2.3],
[0.3, 4.2, 0.0],
];
let scalar = 1.5_f64;
let scalar_mul = matrix![
[4.8, 8.25, 13.8],
[1.65, 0.0, 3.45],
[0.45, 6.3, 0.0],
];
assert_f64_eq!(scalar * &a, scalar_mul);
}
}