How to extract a 2x2 submatrix from a bigger matrix

后端 未结 3 783
醉话见心
醉话见心 2020-12-22 12:16

I am a very basic user and do not know much about commands used in C, so please bear with me...I cant use very complicated codes. I have some knowledge in the stdio.h and ct

3条回答
  •  一生所求
    2020-12-22 13:19

    Let's take this in stages. First a couple of minor fixes to your code:

    for(i=0;i

    Now we define what we want:

    int startrow = 2; /* The starting index. Remember we index 0,1,2,3 */
    int startcol = 2;
    int resultrows = 2; /* How many rows we want in our answer */
    int resultcols = 2;
    float result[resultrows][resultcols];
    

    Now we ignore what we don't want:

    for(i=0;i= startrow && i < startrow + resultrows &&
           j >= startcol && j < startcol + resultcols){
          matrix[i][j] = dummy;
        }
      }
    }
    

    Notice that now only the values we want are copied into matrix, the rest of matrix is uninitialized gibberish. Now write it into result instead:

    for(i=0;i= startrow && i < startrow + resultrows &&
           j >= startcol && j < startcol + resultcols){
          result[i-startrow][j-startcol] = dummy;
        }
      }
    }
    

    EDIT:
    If you want to copy a submatrix from a larger matrix already in memory, the inner loop should be

    for(j=0;j= startrow && i < startrow + resultrows &&
         j >= startcol && j < startcol + resultcols){
          result[i-startrow][j-startcol] = matrix[i][j];
      }
    }
    

提交回复
热议问题