Repository navigation
Expand file tree
/
Copy pathmatrix.rs
More file actions
67 lines (59 loc) · 1.85 KB
/
Copy pathmatrix.rs
File metadata and controls
67 lines (59 loc) · 1.85 KB
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
use crate::core::fields::m31::BaseField;
use crate::core::fields::ExtensionOf;
pub trait SquareMatrix<F: ExtensionOf<BaseField>, const N: usize> {
fn get_at(&self, i: usize, j: usize) -> F;
fn mul(&self, v: [F; N]) -> [F; N] {
(0..N)
.map(|i| {
(0..N)
.map(|j| self.get_at(i, j) * v[j])
.fold(F::zero(), |acc, x| acc + x)
})
.collect::<Vec<_>>()
.try_into()
.unwrap()
}
}
pub struct RowMajorMatrix<F: ExtensionOf<BaseField>, const N: usize> {
values: [[F; N]; N],
}
impl<F: ExtensionOf<BaseField>, const N: usize> RowMajorMatrix<F, N> {
pub fn new(values: Vec<F>) -> Self {
assert_eq!(values.len(), N * N);
Self {
values: values
.chunks(N)
.map(|chunk| chunk.try_into().unwrap())
.collect::<Vec<_>>()
.try_into()
.unwrap(),
}
}
}
impl<F: ExtensionOf<BaseField>, const N: usize> SquareMatrix<F, N> for RowMajorMatrix<F, N> {
fn get_at(&self, i: usize, j: usize) -> F {
self.values[i][j]
}
}
#[cfg(test)]
mod tests {
use crate::core::fields::m31::M31;
use crate::m31;
use crate::math::matrix::{RowMajorMatrix, SquareMatrix};
#[test]
fn test_matrix_multiplication() {
let matrix = RowMajorMatrix::<M31, 3>::new((0..9).map(|x| m31!(x + 1)).collect::<Vec<_>>());
let vector = (0..3)
.map(|x| m31!(x + 1))
.collect::<Vec<_>>()
.try_into()
.unwrap();
let expected_result = [
m31!(14), // 1 * 1 + 2 * 2 + 3 * 3
m31!(32), // 4 * 1 + 5 * 2 + 6 * 3
m31!(50), // 7 * 1 + 8 * 2 + 9 * 3
];
let result = matrix.mul(vector);
assert_eq!(result, expected_result);
}
}