矩阵的转置

对于M\times M的矩阵,使用两个指针变量,可以方便实现(i,j)处元素与(j,i)处元素交换位置。令指针Arow=&A[i][0],则Arow[j]可实现对第i行j列元素的访问。令指针Bptr=&A[0][i],则*Bptr就可以访问(0,i)处元素,然后,令Bptr+=M,就可访问同列不同行的元素。

代码实现

#define M  3
int A[3][3]={{1,2,3},{4,5,6},{7,8,9}};
void transpose(int A[M][M]);

void transpose(int A[M][M])
{
    int i,j;
    int t;
    int *Arow;
    int *Bptr;
    for(i=0;i     {
        Arow=&A[i][0];
       Bptr=&A[0][i];
      for(j=0;j       {
            t=Arow[j];
            Arow[j]=*Bptr;
            *Bptr=t;
            Bptr+=M;
        }
    }
}

void main()
{
    int B[M][M];
    int i,j;
    for(i=0;i      for(j=0;j        B[i][j]=A[i][j];
    transpose(A);            //把A矩阵转置
}

运行结果

B=\begin{bmatrix} 1 & 2 & 3\\ 4& 5 & 6\\ 7& 8& 9 \end{bmatrix}          A=\begin{bmatrix} 1 & 4& 7\\ 2& 5& 8\\ 3& 6 & 9 \end{bmatrix}

你可能感兴趣的:(矩阵,算法,线性代数)