[算法]矩阵求逆 转置 行列式

it2022-05-09  33

#include <stdio.h> #include <stdlib.h> double * MatrixOpp(double *A,int m,int n);     /*矩阵求逆*/ double * MatrixInver(double *A,int m,int n);     /*矩阵转置*/ double Surplus(double A[],int m,int n);     /*求矩阵行列式*/ double * MatrixOpp(double A[],int m,int n) /*矩阵求逆*/ {      int i,j,x,y,k;      double *SP=NULL,*AB=NULL,*B=NULL,X,*C;      SP=(double *)malloc(m*n*sizeof(double));      AB=(double *)malloc(m*n*sizeof(double));      B=(double *)malloc(m*n*sizeof(double));          X=Surplus(A,m,n);      X=1/X;          for(i=0;i<m;i++)      for(j=0;j<n;j++)      {          for(k=0;k<m*n;k++)          B[k]=A[k];          {              for(x=0;x<n;x++)              B[i*n+x]=0;              for(y=0;y<m;y++)              B[m*y+j]=0;              B[i*n+j]=1;              SP[i*n+j]=Surplus(B,m,n);              AB[i*n+j]=X*SP[i*n+j];          }      }      C=MatrixInver(AB,m,n);          return C; }     double * MatrixInver(double A[],int m,int n) /*矩阵转置*/ {      int i,j;      double *B=NULL;      B=(double *)malloc(m*n*sizeof(double));          for(i=0;i<n;i++)      for(j=0;j<m;j++)          B[i*m+j]=A[j*n+i];         return B; }     double Surplus(double A[],int m,int n) /*求矩阵行列式*/ {         int i,j,k,p,r;      double X,temp=1,temp1=1,s=0,s1=0;          if(n==2)      {          for(i=0;i<m;i++)          for(j=0;j<n;j++)              if((i+j)%2) temp1*=A[i*n+j];              else temp*=A[i*n+j];          X=temp-temp1;      }      else      {          for(k=0;k<n;k++)          {              for(i=0,j=k;i<m,j<n;i++,j++)              temp*=A[i*n+j];              if(m-i)              {                  for(p=m-i,r=m-1;p>0;p--,r--)                  temp*=A[r*n+p-1];              }              s+=temp;              temp=1;          }                  for(k=n-1;k>=0;k--)          {              for(i=0,j=k;i<m,j>=0;i++,j--)              temp1*=A[i*n+j];              if(m-i)              {for(p=m-1,r=i;r<m;p--,r++)              temp1*=A[r*n+p];}              s1+=temp1;              temp1=1;          }                 X=s-s1;      }      return X; } /* Test */ int main() {     int i,j;      double arr[5][5], *result, *t=arr;      for(i=0; i<5; i++)      for(j=0; j<5; j++)     scanf("%lf", &arr[i][j]);      result=MatrixOpp((double *)arr,5,5);  //求逆           /*...其他操作,如显示结果*/      printf("\n\nThe result is:\n");      for(i=0; i<5*5; i++)      {                  printf("%lf\t", *(result+i));         if(i%5==4)printf("\n");     }             free(result);      system("PAUSE");      return 0; }

转载于:https://www.cnblogs.com/pancult/archive/2009/02/09/1386768.html

相关资源:c语言编程求矩阵的逆

最新回复(0)