矩阵求逆 转置 行列式

/*
矩阵基本运算: 求逆、转置、计算行列式
*/

#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;
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值