From d6ad12e344ed1e5436d3dc41fc8e978bed0c208c Mon Sep 17 00:00:00 2001 From: Bill Thiede Date: Mon, 5 Jul 2021 15:07:18 -0700 Subject: [PATCH] implement cofactor of 3x3 matrix --- rtchallenge/src/matrices.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) 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;