From bc4f061bcd4d9240b2ea43fbebae84d72f5c9006 Mon Sep 17 00:00:00 2001 From: Jon Janzen Date: Fri, 2 Apr 2021 13:56:19 -0600 Subject: [PATCH] added submatrixes had to use in development features to allow math with const generics --- matrix/src/lib.rs | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/matrix/src/lib.rs b/matrix/src/lib.rs index 260d075..2243c17 100644 --- a/matrix/src/lib.rs +++ b/matrix/src/lib.rs @@ -1,3 +1,6 @@ +#![feature(const_generics)] +#![feature(const_evaluatable_checked)] +#![allow(incomplete_features)] #[macro_use] extern crate approx; @@ -11,6 +14,7 @@ pub struct Matrix { } impl Matrix { + pub fn default() -> Self { Matrix { matrix: [[0f32; W]; H], @@ -46,6 +50,24 @@ impl Matrix { pub fn determinant(&self) -> f32 { 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 Index for Matrix { @@ -336,4 +358,37 @@ mod tests { 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)); + } }