请教各位高人!! 给解释下C#编写矩阵求逆的代码!!越详细越好
/// <summary>/// 求矩阵的逆
/// </summary>
public static double[,] ReverseMatrix(double[,] dMatrix)
{
int a = dMatrix.GetLength(0); int b = dMatrix.GetLength(1);
if (b != a)
{
MessageBox.Show("矩阵行列数不相等,无法求逆!", "错误", MessageBoxButtons.OKCancel,
MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
return null;
}
double dMatrixValue = MatrixValue(dMatrix, a);
if (dMatrixValue == 0) return null;
double[,] dReverseMatrix = new double[a, 2 * a];
double x, c;
// Init Reverse matrix
for (int i = 0; i < a; i++)
{
for (int j = 0; j < 2 * a; j++)
{
if (j < a)
dReverseMatrix[i, j] = dMatrix[i, j];
else
dReverseMatrix[i, j] = 0;
}
dReverseMatrix[i, a + i] = 1;
}
for (int i = 0, j = 0; i < a && j < a; i++, j++)
{
if (dReverseMatrix[i, j] == 0)
{
int m = i;
for (; dMatrix[m, j] == 0; m++) ;
if (m == a)
return null;
else
{
// Add i-row with m-row
for (int n = j; n < 2 * a; n++)
dReverseMatrix[i, n] += dReverseMatrix[m, n];
}
}
// Format the i-row with "1" start
x = dReverseMatrix[i, j];
if (x != 1)
{
for (int n = j; n < 2 * a; n++)
if (dReverseMatrix[i, n] != 0)
dReverseMatrix[i, n] /= x;
}
// Set 0 to the current column in the rows after current row
for (int s = a - 1; s > i; s--)
{
x = dReverseMatrix[s, j];
for (int t = j; t < 2 * a; t++)
dReverseMatrix[s, t] -= (dReverseMatrix[i, t] * x);
}
}
// Format the first matrix into unit-matrix
for (int i = a - 2; i >= 0; i--)
{
for (int j = i + 1; j < a; j++)
if (dReverseMatrix[i, j] != 0)
{
c = dReverseMatrix[i, j];
for (int n = j; n < 2 * a; n++)
dReverseMatrix[i, n] -= (c * dReverseMatrix[j, n]);
}
}
double[,] dReturn = new double[a, a];
for (int i = 0; i < a; i++)
for (int j = 0; j < a; j++)
dReturn[i, j] = dReverseMatrix[i, j + a];
return dReturn;
}
/// <summary>
/// 求逆方法调用的子方法
/// </summary>
public static double MatrixValue(double[,] MatrixList, int a)
{
double[,] dMatrix = new double[a, a];
for (int i = 0; i < a; i++)
for (int j = 0; j < a; j++)
dMatrix[i, j] = MatrixList[i, j];
double c, x;
int k = 1;
for (int i = 0, j = 0; i < a && j < a; i++, j++)
{
if (dMatrix[i, j] == 0)
{
int m = i;
for (; dMatrix[m - 2, j] == 0; m++) ;
if (m == a)
return 0;
else
{
// Row change between i-row and m-row
for (int n = j; n < a; n++)
{
c = dMatrix[i, n];
dMatrix[i, n] = dMatrix[m, n];
dMatrix[m, n] = c;
}
// Change value pre-value
k *= (-1);
}
}
// Set 0 to the current column in the rows after current row
for (int s = a - 1; s > i; s--)
{
x = dMatrix[s, j];
for (int t = j; t < a; t++)
dMatrix[s, t] -= dMatrix[i, t] * (x / dMatrix[i, j]);
}
}
double sn = 1;
for (int i = 0; i < a; i++)
{
if (dMatrix[i, i] != 0)
sn *= dMatrix[i, i];
else
return 0;
}
return k * sn;
}
拜托各位了!!谢谢大家!! --------------------编程问答-------------------- http://topic.csdn.net/u/20100119/17/a4baf73b-fc0e-4fdb-acd1-703faff76e38.html
补充:.NET技术 , C#