Search code examples
c++matrixdimensions

c++ reduce the dimensions of a matrix


I got the following problem: I got a 9x9 matrix which I want to reduce to an 5x5 matrix. I want to this by cancelling the last 3 rows and columns and by cancelling the 3rd row and column. My code looks like this. But it does not work properly.

for (int A=0;A<6;A++)
  for (int B=0;B<6;B++)
      if ((A!=2) || (B!=2))
          disshess5x5(A,B) = disshessian(A,B);

Solution

  • It is always wise to be explicit in what you are trying to implement, so it should be easily readable.

    In this example you should define which rows and columns you want to skip:

    const bool rowToSkip[9] = { false, false, true, false, false, false, true, true, true, true };
    const bool colToSkip[9] {...};
    

    As already answered you should also define source to target index mapping:

    const int tgtRow[9] = {0,1,2,-1,3,4}; // and in the same way tgtCol
    

    With such consts you will get clean loops, easy to spot any errors:

    for(int i = 0; i < 9; ++i)
     if(!rowToSkip[i])
         for (int j = 0; j < 9; ++j)
           if(!colToSkip[j])
             tgtMatrix[tgtRow[i]][tgtCol[j]] = srcMatrix[i][j];
    

    [UPDATE]

    It can be also done in a little faster way by just defining target->source indexes:

    const int srcRow[5] = {0,1,3,4,5};
    const int srcCol[5] = {0,1,3,4,5};
    
    for(int i = 0; i < 5; ++i) 
         for (int j = 0; j < 5; ++j)
             tgtMatrix[i][j] = srcMatrix[srcRow[i]][srcCol[j]];
    

    BTW - your range [0,6) is of length == 6 - you should use [0,5) range to meet 5x5 matrix