C# 矩阵运算求逆 转置
//求逆Inverse
public static double[,] MatrixInverse(double[,] iMatrix)
{
int i = 0;
int row = iMatrix.GetLength(0);
double[,] MatrixZwei = new double[row, row * 2];
double[,] iMatrixInv = new double[row, row];
for (i = 0; i < row; i++)
{
for (int j = 0; j < row; j++)
{
MatrixZwei[i, j] = iMatrix[i, j];
}
}
for (i = 0; i < row; i++)
{
for (int j = row; j < row * 2; j++)
{
MatrixZwei[i, j] = 0;
if (i + row == j)
MatrixZwei[i, j] = 1;
}
}
for (i = 0; i < row; i++)
{
if (MatrixZwei[i, i] != 0)
{
double intTemp = MatrixZwei[i, i];
for (int j = 0; j < row * 2; j++)
{
MatrixZwei[i, j] = MatrixZwei[i, j] / intTemp;
}
}
for (int j = 0; j < row; j++)
{
if (j == i)
continue;
double intTemp = MatrixZwei[j, i];
for (int k = 0; k < row * 2; k++)
{
MatrixZwei[j, k] = MatrixZwei[j, k] - MatrixZwei[i, k] * intTemp;
}
}
}
for (i = 0; i < row; i++)
{
for (int j = 0; j < row; j++)
{
iMatrixInv[i, j] = MatrixZwei[i, j + row];
}
}
return iMatrixInv;
}
//转置
public static double[,] MatrixTranspose(double[,] iMatrix)
{
int row = iMatrix.GetLength(0);
int column = iMatrix.GetLength(1);
//double[,] iMatrix = new double[column, row];
double[,] TempMatrix = new double[row, column];
double[,] iMatrixT = new double[column, row];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
TempMatrix[i, j] = iMatrix[i, j];
}
}
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
iMatrixT[i, j] = TempMatrix[j, i];
}
}
return iMatrixT;
}
// demo
static void Main(string[] args)
{
double[,] matrix = new double[4,4]
{
{ 1, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ 0, 0, 1, 0 },
{ -139, -163, 0.9, 1 },
};
var inverseValue = MatrixInverse(matrix);
var transposeValue = MatrixTranspose(inverseValue);
var lastValue = ConvertTwoArrayToString(transposeValue);
Console.WriteLine(lastValue1);
}
public static string ConvertTwoArrayToString(double[,] matrix)
{
StringBuilder matrixStringValue = new StringBuilder();
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
matrixStringValue.Append(matrix[i, j].ToString());
if (i == 3 && j == 3)
{
continue;
}
matrixStringValue.Append(",");
}
}
return matrixStringValue.ToString();
}
public static double[,] ConvertStringToTwoArray(string originalStr)
{
if (string.IsNullOrWhiteSpace(originalStr))
{
//LogAdapter.Logger.TraceNullOrEmptyParam("originalStr");
throw new IndexOutOfRangeException("original's length can not be zero");
}
//将字符串转换成数组
string[] originalString = originalStr.Split(',');
int x = 4;
int y = 4;
double[,] twoArray = new double[x, y];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
double doubleValue;
double.TryParse(originalString[4 * i + j ], out doubleValue);
twoArray[i, j] = doubleValue;
}
}
return twoArray;
}