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
use crate::{matrix::Matrix, number::Number};
use rayon::prelude::*;
impl<T> Matrix<T>
where
T: Number,
{
pub fn linear_prod(&self, rhs: &Matrix<T>) -> T {
if !self.is_same_size(rhs) {
panic!("dimension mismatch")
} else {
self.elements
.par_iter()
.zip(rhs.elements.par_iter())
.map(|(&s, &r)| s * r)
.sum()
}
}
pub fn hadamard_prod(self, rhs: &Matrix<T>) -> Matrix<T> {
if !self.is_same_size(rhs) {
panic!("dimension mismatch")
}
let mut slf = self;
slf.elements
.par_iter_mut()
.zip(rhs.elements.par_iter())
.map(|(s, &r)| {
*s *= r;
})
.collect::<Vec<_>>();
slf
}
pub fn kronecker_prod(&self, rhs: &Matrix<T>) -> Matrix<T> {
let sn = self.rows;
let sm = self.columns;
let rn = rhs.rows;
let rm = rhs.columns;
let n = sn * rn;
let m = sm * rm;
let mut matrix = Matrix::<T>::zeros(n, m);
for si in 0..sn {
for sj in 0..sm {
for ri in 0..rn {
for rj in 0..rm {
matrix[si * sn + ri][sj * sn + rj] = self[si][sj] * rhs[ri][rj];
}
}
}
}
matrix
}
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
#[test]
fn it_works() {
let a = Matrix::<f64>::identity(2);
let b = Matrix::<f64>::identity(2);
let c = a.hadamard_prod(&b);
assert_eq!(b[0][0], c[0][0])
}
}