输入一矩阵,求它的逆矩阵,求详细代码,最好用C#或者C++描述
发布网友
发布时间:2023-08-15 03:20
我来回答
共1个回答
热心网友
时间:2023-08-26 18:22
求逆所用的代码(C#实现)PS:矩阵行:row 列:col
//得到matrix
public double[,] Detail
{
get { return matrix; }
set { matrix = value; }
}
public static Matrix Inverse(Matrix M)
{
int m = M.row;
int n = M.col;
if (m != n)
{
Exception myException = new Exception("求逆的矩阵不是方阵");
throw myException;
}
Matrix ret = new Matrix(m, n);
double[,] a0 = M.Detail;
double[,] a = (double[,])a0.Clone();
double[,] b = ret.Detail;
int i, j, row, k;
double max, temp;
//单位矩阵
for (i = 0; i < n; i++)
{
b[i, i] = 1;
}
for (k = 0; k < n; k++)
{
max = 0; row = k;
//找最大元,其所在行为row
for (i = k; i < n; i++)
{
temp = Math.Abs(a[i, k]);
if (max < temp)
{
max = temp;
row = i;
}
}
if (max == 0)
{
Exception myException = new Exception("该矩阵无逆矩阵");
throw myException;
}
//交换k与row行
if (row != k)
{
for (j = 0; j < n; j++)
{
temp = a[row, j];
a[row, j] = a[k, j];
a[k, j] = temp;
temp = b[row, j];
b[row, j] = b[k, j];
b[k, j] = temp;
}
}
//首元化为1
for (j = k + 1; j < n; j++) a[k, j] /= a[k, k];
for (j = 0; j < n; j++) b[k, j] /= a[k, k];
a[k, k] = 1;
//k列化为0
//对a
for (j = k + 1; j < n; j++)
{
for (i = 0; i < k; i++) a[i, j] -= a[i, k] * a[k, j];
for (i = k + 1; i < n; i++) a[i, j] -= a[i, k] * a[k, j];
}
//对b
for (j = 0; j < n; j++)
{
for (i = 0; i < k; i++) b[i, j] -= a[i, k] * b[k, j];
for (i = k + 1; i < n; i++) b[i, j] -= a[i, k] * b[k, j];
}
for (i = 0; i < n; i++) a[i, k] = 0;
a[k, k] = 1;
}
return ret;
}