kkk
kkk

Reputation: 35

Matrix Transpose in C

Suppose I define a matrix and assign the value in the following way:

 double A[row * column];

 for (int j = 0; j < column; j++){
     for (int i = 0; i < row; i++){
       A[j*row + i] = ((double)rand())/RAND_MAX; // random value
     }
   }

How can I compute the transpose of this matrix? I have tried the following but the resulting matrix is not correct.

double B[column * row]; 

for(int j = 0; j < row; j++){
     for(int i = 0; i < column; i++){
       B[j*row + i] = A[i*row + j];
     }
   }

Upvotes: 1

Views: 1327

Answers (1)

Codor
Codor

Reputation: 17605

The indexing should be done in the following way.

double B[column * row];

for (int j = 0; j < row; j++){
    for (int i = 0; i < column; i++){
        B[j*column + i] = A[i*row + j];
    }
}

Upvotes: 5

Related Questions