From a584bf54d842b885ce5f0d37bfa5d837db167f8c Mon Sep 17 00:00:00 2001 From: NADAL Jean-Baptiste Date: Fri, 2 Feb 2024 17:41:51 +0100 Subject: [PATCH] [FEAT] Add Submatrix --- raytracing/src/matrix.cpp | 18 ++++++++++++++++++ raytracing/src/matrix.h | 1 + tests/03_matrix.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/raytracing/src/matrix.cpp b/raytracing/src/matrix.cpp index 04faed2..e1fbfa0 100644 --- a/raytracing/src/matrix.cpp +++ b/raytracing/src/matrix.cpp @@ -208,6 +208,24 @@ double Matrix::determinant(void) /* ------------------------------------------------------------------------- */ +Matrix Matrix::sub_matrix(uint8_t a_rows, uint8_t a_cols) +{ + Matrix the_sub = *this; + + the_sub.m_data.erase(the_sub.m_data.begin() + a_rows); + the_sub.m_rows--; + + for (int the_row = 0; the_row < the_sub.m_rows; the_row++) + { + the_sub.m_data[the_row].erase(the_sub.m_data[the_row].begin() + a_cols); + } + the_sub.m_cols--; + + return the_sub; +} + +/* ------------------------------------------------------------------------- */ + Matrix Matrix::identity(void) { Matrix the_identity = { diff --git a/raytracing/src/matrix.h b/raytracing/src/matrix.h index 71d6a82..1754eb3 100644 --- a/raytracing/src/matrix.h +++ b/raytracing/src/matrix.h @@ -61,6 +61,7 @@ namespace Raytracer bool transpose(void); double determinant(void); + Matrix sub_matrix(uint8_t a_rows, uint8_t a_cols); static Matrix identity(void); diff --git a/tests/03_matrix.cpp b/tests/03_matrix.cpp index 31c213e..c8f5a9f 100644 --- a/tests/03_matrix.cpp +++ b/tests/03_matrix.cpp @@ -239,3 +239,41 @@ TEST_CASE("[Matrix] Calculating the determinant of a 2x2 matrix", "[Matrix]") REQUIRE(a.determinant() == 17); } + +/* ------------------------------------------------------------------------- */ + +TEST_CASE("[Matrix] A submatrix of a 3x3 matrix is a 2x2 matrix", "[Matrix]") +{ + Matrix a = { + { 1, 5, 0}, + {-3, 2, 7}, + { 0, 6, -3} + }; + + Matrix b = { + {-3, 2}, + { 0, 6} + }; + + REQUIRE(a.sub_matrix(0, 2) == b); +} + +/* ------------------------------------------------------------------------- */ + +TEST_CASE("[Matrix] A submatrix of a 4x4 matrix is a 3x3 matrix", "[Matrix]") +{ + Matrix a = { + {-6, 1, 1, 6}, + {-8, 5, 8, 6}, + {-1, 0, 8, 2}, + {-7, 1, -1, 1} + }; + + Matrix b = { + {-6, 1, 6}, + {-8, 8, 6}, + {-7, -1, 1} + }; + + REQUIRE(a.sub_matrix(2, 1) == b); +}