Obtaining a submatrix from a squared matrix in C

438 Views Asked by At

I want to find a way to obtain a submatrix from an initial bigger squared matrix in c , more specifically , the bottom right submatrix . Then i want the for cycle to give me all the submatrix that i can obtain from the original squared matrix.

I found some code online :

int initial_matrix[3][3]
int submatrix[2][2];
for( int i = 0; i < R - r + 1; i++){
  for(int j = 0; j < C - c + 1; j++){
    submatrix[i][j]=initial_matrix[i][j]
  }
}

where :

  • R is the number of rows of the initial matrix (so in this case R=3)
  • C is the number of columns of the initial matrix (so in this case C=3)
  • r is the number of rows of the submatrix that i want to obtain (so in this case r=2)
  • c is the number of columns of the submatrix that i want to obtain (so in this case c=2)

But this cycle only gives me the upper left submatrix , while I want the bottom right and then expand it so that it gives me all the possible submatrix of the initial matrix.

1

There are 1 best solutions below

0
Aconcagua On

At first your indices in the loops are not correct! You want to fill in your target matrix rows from indices 0 to r and columns from indices 0 to c so your loops need to look like:

for(size_t i = 0; i < r; ++i)
{
    for(size_t j = 0; j < c; ++j)
    {
        // ...
    }
}

From here on you now can simply assign your target matrix at indices i and j:

submatrix[i][j] = ...;

Problem is that these are not the same indices as in your source matrix (unless you want to use the top-left corner submatrix), so you need to translate the indices to the appropriate positions within the source matrix. Luckily, this is not difficult; if the top-left corner of the submatrix within the source matrix is at row r0 and column c0 then you simply need to add these to the corresponding loop indices, thus you get:

... = initial_matrix[r0 + i][c0 + j];

In your case this would mean e.g. [1 + i][1 + j] to get the bottom-right submatrix with both i and j counting up from 0 to excluded 2 (i.e. counting 0 and 1).