VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之C#求逆矩阵

采用单位矩阵行列式变换求逆矩阵,源码展示:

复制代码
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();
        }
复制代码

测试结果展示:

搜狗截图_2017-01-19_22-04-29


相关教程