added submatrixes

had to use in development features to allow math with const generics
This commit is contained in:
Jon Janzen
2021-04-02 13:56:19 -06:00
parent 704503a9a1
commit bc4f061bcd

View File

@@ -1,3 +1,6 @@
#![feature(const_generics)]
#![feature(const_evaluatable_checked)]
#![allow(incomplete_features)]
#[macro_use] #[macro_use]
extern crate approx; extern crate approx;
@@ -11,6 +14,7 @@ pub struct Matrix<const H: usize, const W: usize> {
} }
impl<const H: usize, const W: usize> Matrix<H, W> { impl<const H: usize, const W: usize> Matrix<H, W> {
pub fn default() -> Self { pub fn default() -> Self {
Matrix { Matrix {
matrix: [[0f32; W]; H], matrix: [[0f32; W]; H],
@@ -46,6 +50,24 @@ impl<const H: usize, const W: usize> Matrix<H, W> {
pub fn determinant(&self) -> f32 { pub fn determinant(&self) -> f32 {
self.matrix[0][0] * self.matrix[1][1] - self.matrix[0][1] * self.matrix[1][0] self.matrix[0][0] * self.matrix[1][1] - self.matrix[0][1] * self.matrix[1][0]
} }
pub fn sub_matrix(&self, skip_row: usize, skip_col: usize) -> Matrix<{H - 1}, {W - 1}>
{
let mut idx_row: usize = 0;
let mut arr = [[0f32; W - 1]; H - 1];
for (i, row) in self.matrix.iter().enumerate().take(W) {
if i == skip_row { continue; }
let mut idx_col: usize = 0;
for (j, col) in row.iter().enumerate().take(W) {
if j == skip_col { continue; }
arr[idx_row][idx_col] = *col;
idx_col += 1;
}
idx_row += 1;
}
Matrix::from_array(arr)
}
} }
impl<const H: usize, const W: usize> Index<usize> for Matrix<H, W> { impl<const H: usize, const W: usize> Index<usize> for Matrix<H, W> {
@@ -336,4 +358,37 @@ mod tests {
assert_eq!(17.0, m.determinant()); assert_eq!(17.0, m.determinant());
} }
#[test]
fn submatrix_3x3() {
let start = Matrix::from_array([
[1.0, 5.0, 0.0],
[-3.0, 2.0, 7.0],
[0.0, 6.0, -3.0],
]);
let expected = Matrix::from_array([
[-3.0, 2.0],
[0.0, 6.0],
]);
assert_eq!(expected, start.sub_matrix(0, 2));
}
#[test]
fn submatrix_4x4() {
let start = Matrix::from_array([
[-6.0, 1.0, 1.0, 6.0],
[-8.0, 5.0, 8.0, 6.0],
[-1.0, 0.0, 8.0, 2.0],
[-7.0, 1.0, -1.0, 1.0],
]);
let expected = Matrix::from_array([
[-6.0, 1.0, 6.0],
[-8.0, 8.0, 6.0],
[-7.0, -1.0, 1.0],
]);
assert_eq!(expected, start.sub_matrix(2, 1));
}
} }