dogmaxpeppe dogmaxpeppe - 1 year ago 65
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:

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:

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 Source

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){
  //TODO check for empty matrix etc;
  for(int i=0;i<MATRIX_HEIGHT; i++)
      //move data to the left
  matrix[i] = realloc(matrix[i], sizeof(double)*MATRIX_WIDHT);
void removeRow(int** matrix, int row){
  //TODO check for empty matrix etc.
    //move data up
    matrix[row] = matrix[row+1];

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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download