C#计算矩阵的逆矩阵

您所在的位置:网站首页 逆矩阵如何求伴随矩阵 C#计算矩阵的逆矩阵

C#计算矩阵的逆矩阵

2024-07-15 11:05| 来源: 网络整理| 查看: 265

1.代码思路

1)对矩阵进行合法性检查:矩阵必须为方阵

2)计算矩阵行列式的值(Determinant函数)

3)只有满秩矩阵才有逆矩阵,因此如果行列式的值为0(在代码中以绝对值小于1E-6做判断),则终止函数,报出异常

4)求出伴随矩阵(AdjointMatrix函数)

5)逆矩阵各元素即其伴随矩阵各元素除以矩阵行列式的商

2.函数代码

(注:本段代码只实现了一个思路,可能并不是该问题的最优解)

/// /// 求矩阵的逆矩阵 /// /// /// public static double[][] InverseMatrix(double[][] matrix) { //matrix必须为非空 if (matrix == null || matrix.Length == 0) { return new double[][] { }; } //matrix 必须为方阵 int len = matrix.Length; for (int counter = 0; counter < matrix.Length; counter++) { if (matrix[counter].Length != len) { throw new Exception("matrix 必须为方阵"); } } //计算矩阵行列式的值 double dDeterminant = Determinant(matrix); if (Math.Abs(dDeterminant) = i ? k + 1 : k]; } } dSum += (matrix[0][i] * dSign * Determinant(matrixTemp)); dSign = dSign * -1; } return dSum; } /// /// 计算方阵的伴随矩阵 /// /// 方阵 /// public static double[][] AdjointMatrix(double [][] matrix) { //制作一个伴随矩阵大小的矩阵 double[][] result = new double[matrix.Length][]; for (int i = 0; i < result.Length; i++) { result[i] = new double[matrix[i].Length]; } //生成伴随矩阵 for (int i = 0; i < result.Length; i++) { for (int j = 0; j < result.Length; j++) { //存储代数余子式的矩阵(行、列数都比原矩阵少1) double[][] temp = new double[result.Length - 1][]; for (int k = 0; k < result.Length - 1; k++) { temp[k] = new double[result[k].Length - 1]; } //生成代数余子式 for (int x = 0; x < temp.Length; x++) { for (int y = 0; y < temp.Length; y++) { temp[x][y] = matrix[x < i ? x : x + 1][y < j ? y : y + 1]; } } //Console.WriteLine("代数余子式:"); //PrintMatrix(temp); result[j][i] = ((i + j) % 2 == 0 ? 1 : -1) * Determinant(temp); } } //Console.WriteLine("伴随矩阵:"); //PrintMatrix(result); return result; } /// /// 打印矩阵 /// /// 待打印矩阵 private static void PrintMatrix(double[][] matrix, string title = "") { //1.标题值为空则不显示标题 if (!String.IsNullOrWhiteSpace(title)) { Console.WriteLine(title); } //2.打印矩阵 for (int i = 0; i < matrix.Length; i++) { for (int j = 0; j < matrix[i].Length; j++) { Console.Write(matrix[i][j] + "\t"); //注意不能写为:Console.Write(matrix[i][j] + '\t'); } Console.WriteLine(); } //3.空行 Console.WriteLine(); }

3.Main函数调用

static void Main(string[] args) { double[][] matrix = new double[][] { new double[] { 1, 2, 3 }, new double[] { 2, 2, 1 }, new double[] { 3, 4, 3 } }; PrintMatrix(matrix, "原矩阵"); PrintMatrix(AdjointMatrix(matrix), "伴随矩阵"); Console.WriteLine("行列式的值为:" + Determinant(matrix) + '\n'); PrintMatrix(InverseMatrix(matrix), "逆矩阵"); Console.ReadLine(); }

4.执行结果

172514_Wtl3_1425762.png



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3