views:

80

answers:

4

i have my code for transposing my matrix:

for(j=0; j<col; j++) { 
    for(k=0; k<row; k++) {
        mat2[j][k] = mat[k][j];
    }

it seems to work on a square matrix but not on a nonsquare matrix. help me guys!

+3  A: 

hope you allocated the arrays of the right dimensions.

@all i know this should be a comment. but i don't have enough reputation points to do so :|

Rahul
You have enough rep now. 8v)
Fred Larson
A: 

If col is the number of rows in mat2 (and columns in mat) and row is the number of columns in mat2 (and rows in mat), then this should work.

You need an extra close curly, but I assume you have that in your code.

Lou Franco
+3  A: 

It will work for a non-square matrix, but you have to ensure that the number of rows in mat2 matches the number of columns in mat, and vice versa. I.e., if mat is an NxM matrix, then mat2 must be an MxN matrix.

Jerry Coffin
+1  A: 

Is that the actual code you have used in your application? Because it's wrong.
The syntax for the for statement is:

for (Initialization; Condition to continue with the loop; Step Operation) {}

In your case you should use something like this:

#define COLS 10
#define ROWS 5

int mat[COLS][ROWS];
int mat2[ROWS][COLS];

int i, j;

for (i = 0; i < COLS; i ++) {
    for (j = 0; j < ROWS; j++) {
        mat2[j][i] = mat[i][j];
    }
}

This way this could transpose your matrix. Naturally this way you need to know beforehand the dimensions for the matrix. Another way could be to dinamically initialize your matrix by using some User provided data, like this:

int ** mat;
int ** mat2;

int cols, rows;
int i, j;

/* Get matrix dimension from the user */

mat = (int **) malloc (sizeof(int *) * cols);

for (i = 0; i < cols; i++) {
    mat[i] = (int *) malloc (sizeof(int) * rows);
}

This way you'll dinamically initialize a matrix and then you can transpose it the same way as before.

Jazzinghen
Oh, I've seen you've updated your code. The second part of the answer could be of help...
Jazzinghen