C#计算矩阵的逆矩阵方法实例分析

本文实例讲述了C#计算矩阵的逆矩阵方法。分享给大家供大家参考。具体如下:

1.代码思路

1)对矩阵进行合法性检查:矩阵必须为方阵
2)计算矩阵行列式的值(Determinant函数)
3)只有满秩矩阵才有逆矩阵,因此如果行列式的值为0(在代码中以绝对值小于1E-6做判断),则终止函数,报出异常
4)求出伴随矩阵(AdjointMatrix函数)
5)逆矩阵各元素即其伴随矩阵各元素除以矩阵行列式的商

2.函数代码

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

/// <summary>
/// 求矩阵的逆矩阵
/// </summary>
/// <param name="matrix"></param>
/// <returns></returns>
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) <= 1E-6)
 {
  throw new Exception("矩阵不可逆");
 }
 //制作一个伴随矩阵大小的矩阵
 double[][] result = AdjointMatrix(matrix);
 //矩阵的每项除以矩阵行列式的值,即为所求
 for (int i = 0; i < matrix.Length; i++)
 {
  for (int j = 0; j < matrix.Length; j++)
  {
   result[i][j] = result[i][j] / dDeterminant;
  }
 }
 return result;
}
/// <summary>
/// 递归计算行列式的值
/// </summary>
/// <param name="matrix">矩阵</param>
/// <returns></returns>
public static double Determinant(double[][] matrix)
{
 //二阶及以下行列式直接计算
 if (matrix.Length == 0) return 0;
 else if (matrix.Length == 1) return matrix[0][0];
 else if (matrix.Length == 2)
 {
  return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
 }
 //对第一行使用“加边法”递归计算行列式的值
 double dSum = 0, dSign = 1;
 for (int i = 0; i < matrix.Length; i++)
 {
  double[][] matrixTemp = new double[matrix.Length - 1][];
  for (int count = 0; count < matrix.Length - 1; count++)
  {
   matrixTemp[count] = new double[matrix.Length - 1];
  }
  for (int j = 0; j < matrixTemp.Length; j++)
  {
   for (int k = 0; k < matrixTemp.Length; k++)
   {
    matrixTemp[j][k] = matrix[j + 1][k >= i ? k + 1 : k];
   }
  }
  dSum += (matrix[0][i] * dSign * Determinant(matrixTemp));
  dSign = dSign * -1;
 }
 return dSum;
}
/// <summary>
/// 计算方阵的伴随矩阵
/// </summary>
/// <param name="matrix">方阵</param>
/// <returns></returns>
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;
}
/// <summary>
/// 打印矩阵
/// </summary>
/// <param name="matrix">待打印矩阵</param>
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.执行结果

希望本文所述对大家的C#程序设计有所帮助。

(0)

相关推荐

  • c#获取数组中最大数的值

    求数组中最大的数的值:1.数组的max函数: 复制代码 代码如下: class Program    {        static void Main(string[] args)        {            int[] array = {1,3,5,2,4,6,7,9,0,8};           int max= GetMax(array);            Console.WriteLine("数组中最大的值是{0}",max);            Co

  • C#中计算时间差中的小数问题解决

    问题: startTime = DateTime.Now;            -----------slExecutedTime.Text = (DateTime.Now - startTime).ToString();执行结果:已执行:00:00:03.1234434(后面会多出很多的小数位)想要的执行结果:已执行:00:00:03 -------------------------------------------------------------------------------

  • C#计算器编写代码

    利用C#编写一个计算器.如下图,能够完成基本的四则运算. 当然这个程序甚至还不上Windows附件那个自带的多功能计算器.  不过这个程序的逻辑还是非常值得思考的,首先你要考虑好用户按+ - * / =等运算符号.数字键之后计算器的状态记录问题.  然后要防止多次按某一个键的问题.比如小数点.就不应该让用户在输入一个数的时候键入两次.  最后,还要弄两个数组,一个存放用户在输入的数字,另一个存放用户输入的符号.  制作过程如下,  1.布局如下,同时可以参考<简单实现C#窗体程序判断是否闰年 >

  • c#求两个数中最大值的方法

    1.三元运算符: 复制代码 代码如下: class Program    {        static void Main(string[] args)        {          int max= NumMAX(10,15);            Console.WriteLine("最大数:{0}",max);            Console.ReadKey();        }   /// <summary>        /// 两个数中最大的值

  • C#实现输入10个数存入到数组中并求max和min及平均数的方法示例

    本文实例讲述了C#实现输入10个数存入到数组中并求max和min及平均数的方法.分享给大家供大家参考,具体如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int nu1, max,min,number;

  • C#使用linq计算执行元素在列表中出现次数的方法

    本文实例讲述了C#使用linq计算执行元素在列表中出现次数的方法.分享给大家供大家参考.具体如下: 这是使用linq计算元素在列表中出现的次数,调用方法非常简单,和sql语句很像 复制代码 代码如下: // Count the number of times an item appears in this list public static int CountTimes<T>(this List<T> inputList, T searchItem) { return ((fro

  • C#实现Winform版计算器

    本文实例为大家分享Winform版计算器的具体实现方法,供大家参考,具体内容如下 前台页面设计 后台代码实现 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace 计

  • C#获取数组中最大最小值的方法

    根据下面函数获取数组中最大最小值即可.调用时候直接传数组范围一个float类型的变量 public float MaxOfList(float[] flotNum) { float maxValue = flotNum.ToArray().Max(); return maxValue; } public float MinOfList(float[] flotNum) { float minValue = flotNum.ToArray().Max(); for (int i = 0; i <

  • C#求n个数中最大值和最小值的方法

    本文实例讲述了C#求n个数中最大值和最小值的方法.分享给大家供大家参考.具体实现方法如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Console.WriteLine("输入十个数: "); /

  • C#实现计算年龄的简单方法汇总

    vs2010测试通过,主要思想是由出生日期和当前日期,两个日期计算出年龄(岁.月.天) using System; using System.Collections.Generic; using System.Text; namespace PublicClass { public static class CalculationDate { /// <summary> /// 由两个日期计算出年龄(岁.月.天) /// </summary> public static void

  • C#基于面向过程计算加权平均分的方法

    本文实例讲述了C#基于面向过程计算加权平均分的方法.分享给大家供大家参考.具体如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("输入你的总共课程数:"); i

随机推荐