Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My algorithm for transposing matrix only works on certain dimensions

Basically, I have written some code to transpose a matrix and for some inputs it works, for some it does not, i have no clue where did i make a mistake.

This is the code

#include <stdio.h>

int main() {
  int WIDTH, HEIGHT, i, j;
  int matrix[100][100];
  do {
    printf("Enter height and width: ");
    scanf("%d %d", &HEIGHT, &WIDTH);
    if ((WIDTH > 100 || HEIGHT > 100) || (WIDTH < 1) || (HEIGHT < 1))
      printf("Dimensions incorrect!\n");
    else
      break;
  } while (1);

  int vel = WIDTH * HEIGHT;

  printf("Enter elements: ");
  for (i = 0; i < HEIGHT; i++)
    for (j = 0; j < WIDTH; j++)
      scanf("%d", &matrix[i][j]);

  int temp;
  for (i = 0; i < HEIGHT; i++) {
    for (j = i; j < WIDTH; j++) {
      temp = matrix[i][j];
      matrix[i][j] = matrix[j][i];
      matrix[j][i] = temp;
    }
  }

  printf("Transposed matrix: \n");
  for (i = 0; i < WIDTH; i++) {
    for (j = 0; j < HEIGHT; j++)
      printf("%5d", matrix[i][j]);
    printf("\n");
  }

  return 0;
}

My output for dimensions 3 2, elements {1,2,3,4,5,6}: (example 1)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1    3    0
2    4    0

Wanted output: (example 1)

1    3    5
2    4    6

My output for dimensions 5 1, elements {1,2,3,4,5}:
(example 2)

1    0    0    0    0

Wanted output: (example 2)

1    2    3    4     5

>Solution :

Consider the 5,1 case, so:

  for (i = 0; i < 5; i++) {
    for (j = i; j < 1; j++) { // for j>=1 the condition will always fail
      temp = matrix[i][j];
      matrix[i][j] = matrix[j][i];
      matrix[j][i] = temp;
    }
  }

The body of the inner loop will only run for [0][0].

That loop will only work if HEIGHT<=WIDTH. If HEIGHT>=WIDTH, you should instead do:

  for (i = 0; i < HEIGHT; i++) {
    for (j = 0; j < i; j++) {
      temp = matrix[i][j];
      matrix[i][j] = matrix[j][i];
      matrix[j][i] = temp;
    }
  }

In other words, if the matrix is asymmetric you want to base the number of swaps on its longer side.

If HEIGHT==WIDTH, you can do either one.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading