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
pub mod bd;
pub mod ci;
pub mod di;
pub mod ge;
pub mod kr;
pub mod operations;
pub mod operators;
pub mod po;
pub mod pt;
pub mod st;
pub mod sy;
pub mod to;
pub mod tr;
use crate::number::{c64, Number};
use rayon::prelude::*;
#[derive(Clone, Debug, Default, Hash)]
pub struct Matrix<T = f64>
where
T: Number,
{
rows: usize,
cols: usize,
elems: Vec<T>,
}
impl<T> Matrix<T>
where
T: Number,
{
pub fn new(rows: usize, cols: usize) -> Self {
Self {
rows,
cols,
elems: vec![T::default(); rows * cols],
}
}
pub fn from(rows: usize, elems: Vec<T>) -> Self {
Self {
rows,
cols: elems.len() / rows,
elems,
}
}
pub fn row(v: Vec<T>) -> Self {
Matrix::<T>::from(1, v)
}
pub fn col(v: Vec<T>) -> Self {
Matrix::<T>::from(v.len(), v)
}
pub fn same_size(&self, rhs: &Matrix<T>) -> bool {
self.rows == rhs.rows && self.cols == rhs.cols
}
pub fn rows(&self) -> usize {
self.rows
}
pub fn cols(&self) -> usize {
self.cols
}
pub fn elems(self) -> Vec<T> {
self.elems
}
pub fn elems_ref(&self) -> &[T] {
&self.elems
}
}
impl Matrix<f64> {
pub fn to_complex(&self) -> Matrix<c64> {
Matrix::<c64>::from(
self.rows,
self.elems.par_iter().map(|&e| c64::new(e, 0.0)).collect(),
)
}
}
impl Matrix<c64> {
pub fn to_real(&self) -> Matrix<f64> {
Matrix::from(self.rows, self.elems.par_iter().map(|e| e.re).collect())
}
}