dogmaxpeppe dogmaxpeppe - 3 months ago 7
C Question

Delete a column and a row in a square matrix in C

I had a square matrix typed dynamically, correctly allocated

double **matrix;


I want to delete a "x" row and "x" column from that matrix, in a way like that:

SOURCE MATRIX:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16


I want to remove, for example, the 2nd row/column. The output had to be like this:

FINAL MATRIX:
1 3 4
9 11 12
13 15 16


I've tried to write down and test many algorithms, without success.
How can I do?

Answer

Well, to do this, you'll have to realise that in memory your matrix is actually a list of lists. This means that removing a column is slightly different from removing a row:

Assuming your syntax is matrix[row][column];

void removeColumn(int** matrix, int col){
  MATRIX_WIDTH--;
  //TODO check for empty matrix etc;
  for(int i=0;i<MATRIX_HEIGHT; i++)
  {
    while(col<MATRIX_WIDTH)
    {
      //move data to the left
      matrix[i][col]=matrix[i][col+1];
      col++;
    }
  matrix[i] = realloc(matrix[i], sizeof(double)*MATRIX_WIDHT);
  }
void removeRow(int** matrix, int row){
  MATRIX_HEIGHT--;
  //TODO check for empty matrix etc.
  free(matrix[row]);
  while(row<MATRIX_HEIGHT)
  {
    //move data up
    matrix[row] = matrix[row+1];
    row++;
  }
}

so removeColumn iterates over each row, and deletes the appropriate item, and removeRow can just free the row, and overwrite its pointer.

NOTE that you have to keep track of the size of the matrix size yourself. In the example i used MATRIX_WIDTH and MATRIX_HEIGHT but you'll have to implement something for this. (Maybe a struct with width height and pointer in it.)

Comments