code_transpiler/
matrix.rs1#[derive(Debug, Clone, PartialEq)]
2pub struct Matrix {
3 pub rows: usize,
4 pub cols: usize,
5 pub data: Vec<f64>,
6}
7
8impl Matrix {
9 pub fn new(rows: usize, cols: usize) -> Self {
10 Self {
11 rows,
12 cols,
13 data: vec![0.0; rows.saturating_mul(cols)],
14 }
15 }
16 pub fn from_vec(rows: usize, cols: usize, data: Vec<f64>) -> Result<Self, String> {
17 if rows.checked_mul(cols) != Some(data.len()) {
18 return Err("matrix dimensions do not match data length".into());
19 }
20 Ok(Self { rows, cols, data })
21 }
22 pub fn at(&self, row: usize, col: usize) -> f64 {
23 self.data[row * self.cols + col]
24 }
25 pub fn set(&mut self, row: usize, col: usize, value: f64) {
26 self.data[row * self.cols + col] = value;
27 }
28 pub fn valid(&self) -> bool {
29 self.rows.checked_mul(self.cols) == Some(self.data.len())
30 }
31 pub fn multiply(&self, rhs: &Matrix) -> Result<Matrix, String> {
32 if self.cols != rhs.rows {
33 return Err("matrix shape mismatch".into());
34 }
35 let mut out = Matrix::new(self.rows, rhs.cols);
36 for r in 0..self.rows {
37 for c in 0..rhs.cols {
38 let mut sum = 0.0;
39 for k in 0..self.cols {
40 sum += self.at(r, k) * rhs.at(k, c);
41 }
42 out.set(r, c, sum);
43 }
44 }
45 Ok(out)
46 }
47}
48
49#[derive(Debug, Clone, PartialEq)]
50pub struct SparseMatrix {
51 pub rows: usize,
52 pub cols: usize,
53 pub entries: Vec<(usize, usize, f64)>,
54}
55impl SparseMatrix {
56 pub fn new(rows: usize, cols: usize) -> Self {
57 Self {
58 rows,
59 cols,
60 entries: Vec::new(),
61 }
62 }
63 pub fn set(&mut self, row: usize, col: usize, value: f64) {
64 if let Some(e) = self.entries.iter_mut().find(|e| e.0 == row && e.1 == col) {
65 e.2 = value;
66 } else if value != 0.0 {
67 self.entries.push((row, col, value));
68 }
69 }
70 pub fn at(&self, row: usize, col: usize) -> f64 {
71 self.entries
72 .iter()
73 .find(|e| e.0 == row && e.1 == col)
74 .map(|e| e.2)
75 .unwrap_or(0.0)
76 }
77 pub fn multiply(&self, rhs: &SparseMatrix) -> Result<SparseMatrix, String> {
78 if self.cols != rhs.rows {
79 return Err("sparse matrix shape mismatch".into());
80 }
81 let mut out = SparseMatrix::new(self.rows, rhs.cols);
82 for r in 0..self.rows {
83 for c in 0..rhs.cols {
84 let mut sum = 0.0;
85 for k in 0..self.cols {
86 sum += self.at(r, k) * rhs.at(k, c);
87 }
88 if sum != 0.0 {
89 out.set(r, c, sum);
90 }
91 }
92 }
93 Ok(out)
94 }
95}