/*
* File Name: Matrix_Transpose
* Author: MH
* Since 2011/03/21
* Toolkit: Dev C++
*/
# include <stdlib.h>
# include <stdio.h>
int main(){
int i, j, count=0, temp;
int c[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
printf("before transposing\n");
for(i=0; i<3; i++){
printf("|");
for(j=0; j<3; j++){
printf("% -3d", c[i][j]);
}
printf("|\n");
}
printf("\nafter transposing\n");
for(i=0; i<3; i++){
for(j=i; j<3; j++){
temp = c[i][j];
c[i][j] = c[j][i];
c[j][i] = temp;
count++;
}
}
for(i=0; i<3; i++){
printf("|");
for(j=0; j<3; j++){
printf("% -3d", c[i][j]);
}
printf("|\n");
}
printf("\ncount of swaps = %d times\n\n", count);
system("Pause");
return 0;
}
在作矩陣轉置的時候,常會有人在第二層迴圈時寫成
for(i=0; i<3; i++){
for(j=0; j<3; j++){
temp = c[i][j];
c[i][j] = c[j][i];
c[j][i] = temp;
count++;
}
}
這樣會造成轉置後的元素再被轉置一次,所以執行時會發現矩陣根本沒變,因此轉過的就不用再轉了,這就是第二層設成j=i的原因
另外方正矩陣對角線轉置之後還是自己,所以i=j時其實是不用轉的,可以將程式碼改成下面的形式
printf("\nafter transposing\n");
for(i=0; i<3; i++){
for(j=i+1; j<3; j++){
temp = c[i][j];
c[i][j] = c[j][i];
c[j][i] = temp;
count++;
}
}
如此一來可以減少不必要的轉置
沒有留言:
張貼留言