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
pub mod operations;
pub mod operators;

use crate::number::{c64, Number};
use crate::types::{Standard, Type};
use rayon::prelude::*;
use std::marker::PhantomData;

/// # Matrix
#[derive(Clone, Debug, Default, Hash)]
pub struct Matrix<T = Standard, U = f64>
where
    T: Type,
    U: Number,
{
    rows: usize,
    columns: usize,
    elements: Vec<U>,
    phantom: PhantomData<T>,
}

impl<T, U> Matrix<T, U>
where
    T: Type,
    U: Number,
{
    pub fn new(rows: usize, columns: usize, elements: Vec<U>) -> Self {
        Self {
            rows,
            columns,
            elements,
            phantom: PhantomData,
        }
    }

    pub fn is_same_size<V: Type>(&self, rhs: &Matrix<V, U>) -> bool {
        self.rows == rhs.rows && self.columns == rhs.columns
    }

    pub fn get_rows(&self) -> usize {
        self.rows
    }

    pub fn get_columns(&self) -> usize {
        self.columns
    }

    pub fn get_elements(&mut self) -> &mut [U] {
        &mut self.elements
    }
}

impl<T> Matrix<T, f64>
where
    T: Type,
{
    pub fn to_complex(&self) -> Matrix<T, c64> {
        Matrix::<T, c64>::new(
            self.rows,
            self.columns,
            self.elements
                .par_iter()
                .map(|&e| c64::new(e, 0.0))
                .collect(),
        )
    }
}

impl<T> Matrix<T, c64>
where
    T: Type,
{
    pub fn to_real(&self) -> Matrix<T, f64> {
        Matrix::<T, f64>::new(
            self.rows,
            self.columns,
            self.elements.par_iter().map(|e| e.re).collect(),
        )
    }
}

pub trait Vector<U: Number> {
    fn to_row_vector(&self) -> Matrix<Standard, U>;
    fn to_column_vector(&self) -> Matrix<Standard, U>;
}

impl<U: Number> Vector<U> for [U] {
    fn to_row_vector(&self) -> Matrix<Standard, U> {
        Matrix::<Standard, U>::new(1, self.len(), self.to_vec())
    }

    fn to_column_vector(&self) -> Matrix<Standard, U> {
        Matrix::<Standard, U>::new(self.len(), 1, self.to_vec())
    }
}