diff --git a/rtchallenge/src/matrices.rs b/rtchallenge/src/matrices.rs index 475ae54..223fe6b 100644 --- a/rtchallenge/src/matrices.rs +++ b/rtchallenge/src/matrices.rs @@ -82,6 +82,7 @@ impl Matrix3x3 { Matrix2x2 { m } } + /// Compute minor of a 3x3 matrix. /// /// # Examples /// ``` @@ -95,6 +96,23 @@ impl Matrix3x3 { pub fn minor(&self, row: usize, col: usize) -> f32 { self.submatrix(row, col).determinant() } + + /// Compute cofactor of a 3x3 matrix. + /// + /// # Examples + /// ``` + /// use rtchallenge::matrices::{Matrix2x2, Matrix3x3}; + /// + /// let a = Matrix3x3::new([3., 5., 0.], [2., -1., -7.], [6., -1., 5.]); + /// assert_eq!(a.minor(0, 0), -12.); + /// assert_eq!(a.cofactor(0, 0), -12.); + /// assert_eq!(a.minor(1, 0), 25.); + /// assert_eq!(a.cofactor(1, 0), -25.); + /// ``` + pub fn cofactor(&self, row: usize, col: usize) -> f32 { + let negate = if (row + col) % 2 == 0 { 1. } else { -1. }; + self.submatrix(row, col).determinant() * negate + } } impl Index<(usize, usize)> for Matrix3x3 { type Output = f32;