採用單位矩陣行列式變換求逆矩陣,源碼展示: public static double[,] Inverse(double [,] Array) { int m = 0; int n = 0; m = Array.GetLength(0); n = Array.GetLength(1);... ...
採用單位矩陣行列式變換求逆矩陣,源碼展示:
public static double[,] Inverse(double [,] Array) { int m = 0; int n = 0; m = Array.GetLength(0); n = Array.GetLength(1); double[,] array = new double[2*m+1, 2*n+1]; for (int k = 0; k < 2*m+1; k++) //初始化數組 { for (int t = 0; t < 2*n+1; t++) { array[k, t] = 0.00000000; } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { array[i, j] = Array[i, j]; } } for (int k = 0; k < m; k++) { for (int t = n; t <= 2*n; t++) { if ((t - k) == m) { array[k, t] = 1.0; } else { array[k, t] = 0; } } } //得到逆矩陣 for (int k = 0; k < m; k++) { if (array[k, k] != 1) { double bs = array[k, k]; array[k, k] = 1; for (int p = k + 1; p < 2*n; p++) { array[k, p] /= bs; } } for (int q = 0; q < m; q++) { if (q != k) { double bs = array[q, k]; for (int p = 0; p < 2*n; p++) { array[q, p] -= bs * array[k, p]; } } else { continue; } } } double [,] NI = new double[m, n]; for (int x = 0; x < m; x++) { for (int y = n; y < 2*n; y++) { NI[x, y - n] = array[x, y]; } } return NI; }
測試代碼:
static void Main(string[] args) { double[,] a = new double[3, 3] { { 1, 2, 3 }, { 2, 2, 1 }, { 3, 4, 3 } };//測試數組 double [,] dReturn = Inverse(a); for (int i = 0; i < a.GetLength(0);i++ ) { for (int j = 0; j < a.GetLength(1); j++) { Console.Write(dReturn[i,j]+ "\t "); } Console.WriteLine(); } Console.ReadKey(); }
測試結果展示: