# 求AX=B中X。计算矩阵的秩，用高斯消元法求A的逆，X=A的逆*B

1. 这个里面的a一直到p都是表示数组里的数，不是变量名
2. 带圆圈的数字表示矩阵all这一整行
3. 0<=k<2n的条件下，是a [j][k] = a[j][k] - (a[j[i]/a[i][i])*a[i][k];
4. 这张草稿只是草稿，难免有错，意思就是那个意思
5. 在计算的时候，只能把数组元素的值赋给其他的变量，用其他的变量计算，你们可以试试，反正code blocks不行
6. 要是有大佬可以用动态数组做，就可以不用宏定义n和n1，直接输入A和B矩阵，判断n和n1的大小来计算就行了。我还不会，有会的，能不能教教我
7. 本来想用函数去做，但是返回的时候，比较困难，所以我直接在main函数里面做了

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define n 4
#define n1 2
int main()
{
double A[n][n] = {{1,3,2,13},{7,2,1,-3},{9,15,3,-2},{-2,-2,11,5}};//you can change  matrix A and B ,number n and n1 to do other matrix
double B[n][n1] = {{9,0},{6,4},{11,7},{-2,-1}};
double X[n][n1];
double a[n][2*n]={{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0}};
int i,j,k;
double t,t1,t2;
//calculate rank first
//but I think maybe we dont have to do that,because when the rank doesnt comfort to the question, we get answer like    -1.#IND00
//we can still calculate the rank as we wish
for(i=0;i<n;i++)
{
t=A[i][i];//get the numbers from diagonal line
for(j=i+1;j<n;j++)
{
t1=A[j][i];//get the each number below A[i][i]
for(k=0;k<n;k++)//do this for every number in each row
{
t2=A[i][k];//get each number in the array
A[j][k] = A[j][k] - (t1/t)*t2;//let numbers below the diagonal line to be 0
}
}
}
int count=0;//to figure out how many zeros are there in the diagonal line
for(i=0;i<n;i++)
{
if(A[i][i]==0) count++;//这个地方是可以改的，如果你改成if(A[i][i]!=0) count++;再把下面这行删掉，在for循环结束后打印count就知道矩阵的秩了
if(count==1) {printf("这个A的秩不满足有逆矩阵的条件");return 0;}
}

for(i=0;i<n;i++)//this loop get the whole matrix to do the Gaussian elimination
{
for(j=0;j<n;j++)
{
a[i][j]=A[i][j];
}
a[i][n+i]=1;
}// now the all matrix is ready to figure out the reverse matrix of A matrix
for(i=0;i<n;i++)
{
t=a[i][i];//get the number in the diagonal line
for(j=0;j<n;j++)
{
if(j!=i)//every row that is not row i
{
t1=a[j][i];//get the numbers in the column except those belong to the diagonal line
for(k=0;k<2*n;k++)//do the math for the whole row
{
t2=a[i][k];
a[j][k] = a[j][k] - (t1/t)*t2;// you can only do math when you have variables, you cannot use the array elements directly to do the math
}
}
}
}
//now we have the diagonal matrix
for(i=0;i<n;i++)//对一行的每一个数字，除以左边对角矩阵的每一行对角线上的值
{
t=a[i][i];
for(k=0;k<2*n;k++)
{
a[i][k] = a[i][k]/t;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
A[i][j] = a[i][j+n];
}
}
//Now we already get the reverse matrix A
//use A to left multiply B to get X
double sum;
for(k=0;k<n1;k++)
{
for(i=0;i<n;i++)
{
sum=0;
for(j=0;j<n;j++)
{
t1=A[i][j];
t2=B[j][k];
sum=sum+t1*t2;
}
X[i][k]=sum;
}
}
for(i=0;i<n;i++)
{
for(k=0;k<n1;k++)
{
t=X[i][k];
printf("%lf\t",t);
}
printf("\n");
}
return 0;
}



©️2019 CSDN 皮肤主题: 1024 设计师: 上身试试