Advertisement
ulfben

submatrix second version

Feb 5th, 2023 (edited)
988
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //submatrix second version
  2.  
  3. constexpr value_type operator[](size_type i) const noexcept {
  4.     assert(i < size());
  5.     return _data[i];
  6. }
  7. constexpr reference operator[](size_type i) noexcept {
  8.     assert(i < size());
  9.     return _data[i];
  10. }
  11.  
  12. constexpr size_type index_to_column(size_type index) const noexcept {
  13.     assert(index < size());
  14.     return index % columns();
  15. }
  16. constexpr size_type index_to_row(size_type index) const noexcept {
  17.     assert(index < size());
  18.     return index / columns();
  19. }
  20.        
  21. constexpr auto submatrix(size_type remove_row, size_type remove_column) const noexcept {
  22.     assert(remove_row < rows() && remove_column < columns() && "submatrix: row and column to remove must be inside the original matrix.");
  23.     Matrix<ROWS - 1, COLUMNS - 1> r;          
  24.     uint8_t ri = 0;
  25.     for (size_type i = 0; i < size(); i++) {
  26.         if(index_to_row(i) != remove_row && index_to_column(i) != remove_column) {
  27.             r[ri++] = _data[i];
  28.         }
  29.     }    
  30.     return r;
  31. }
  32.  
  33. TEST(Matrix, getRowFromIndex) {
  34.     const Matrix3 a{
  35.         1,5,0,
  36.         -3,2,7,
  37.         0,6,-3
  38.     };    
  39.     EXPECT_EQ(0, a.index_to_row(0));
  40.     EXPECT_EQ(0, a.index_to_row(2));
  41.     EXPECT_EQ(2, a.index_to_row(6));
  42.     EXPECT_EQ(2, a.index_to_row(8));    
  43. }
  44.  
  45. TEST(Matrix, getColumnFromIndex) {
  46.     const Matrix3 a{
  47.         1,5,0,
  48.         -3,2,7,
  49.         0,6,-3
  50.     };    
  51.     EXPECT_EQ(0, a.index_to_column(0));
  52.     EXPECT_EQ(1, a.index_to_column(1));
  53.     EXPECT_EQ(2, a.index_to_column(2));
  54.     EXPECT_EQ(0, a.index_to_column(6));
  55.     EXPECT_EQ(1, a.index_to_column(7));
  56.     EXPECT_EQ(2, a.index_to_column(8));
  57. }
  58.  
  59. TEST(Matrix, submatrixOf3x3is2x2) {
  60.     const Matrix3 a{
  61.         1,5,0,
  62.         -3,2,7,
  63.         0,6,-3
  64.     };
  65.     const Matrix2 truth{
  66.         -3, 2,
  67.         0, 6
  68.     };
  69.     const auto b = submatrix(a, 0, 2);
  70.     const auto c = a.submatrix(0, 2);
  71.     EXPECT_TRUE(b == truth);
  72.     EXPECT_TRUE(c == truth);
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement