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
use std::ops::{
Add,
Sub,
Mul,
Index,
IndexMut,
};
use crate::error::*;
#[derive(Clone, Debug)]
pub struct Matrix {
rows: usize,
cols: usize,
vals: Vec<f64>,
}
impl Matrix {
pub fn new(rows: usize, cols: usize, vals: Vec<f64>) -> Self {
Self {
rows,
cols,
vals,
}
}
pub fn scalar_multiply(&self, scalar: f64) -> Self {
let vals = self.vals.iter().map(|x| scalar*x).collect::<Vec<f64>>();
Self {
vals,
..*self
}
}
pub fn rows(&self) -> usize {
self.rows
}
pub fn cols(&self) -> usize {
self.cols
}
pub fn copy_vals(&self) -> Vec<f64> {
self.vals.to_owned()
}
pub fn vals(&self) -> &Vec<f64> {
&self.vals
}
pub fn vals_mut(&mut self) -> &mut Vec<f64> {
&mut self.vals
}
}
impl Add for Matrix {
type Output = Self;
fn add(self, other: Self) -> Self {
if self.rows() != other.rows() || self.cols() != other.cols() {
throw(ImproperDimensions);
Self::new(0, 0, Vec::new());
}
let mut output_vals = Vec::new();
for (i, j) in self.vals().iter().zip(other.vals().iter()) {
output_vals.push(i + j);
}
Self {
vals: output_vals,
..self
}
}
}
impl Sub for Matrix {
type Output = Self;
fn sub(self, other: Self) -> Self {
if self.rows() != other.rows() || self.cols() != other.cols() {
throw(ImproperDimensions);
Self::new(0, 0, Vec::new());
}
let mut output_vals = Vec::new();
for (i, j) in self.vals().iter().zip(other.vals().iter()) {
output_vals.push(i - j);
}
Self {
vals: output_vals,
..self
}
}
}
impl Mul for Matrix {
type Output = Self;
#[allow(unused_variables)]
fn mul(self, other: Self) -> Self {
Self::new(0, 0, Vec::new())
}
}
impl Index<[usize; 2]> for Matrix {
type Output = f64;
fn index(&self, index: [usize; 2]) -> &Self::Output {
let i = index[0];
let j = index[1];
&self.vals()[i*self.cols() + j]
}
}
impl IndexMut<[usize; 2]> for Matrix {
fn index_mut(&mut self, index: [usize; 2]) -> &mut Self::Output {
let i = index[0];
let j = index[1];
let cols = self.cols();
&mut self.vals_mut()[i*cols + j]
}
}