程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#求逆矩陣,

C#求逆矩陣,

編輯: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();
        }

測試結果展示:

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved