C#程式實現矩陣乘法


矩陣乘法程式用於計算兩個矩陣的乘積。此操作只有在第一個矩陣的列數等於第二個矩陣的行數時才可進行。

下面給出一個演示C#中矩陣乘法的程式示例:

示例

 線上演示

using System;
namespace MatrixMultiplicationDemo {
   class Example {
      static void Main(string[] args) {
         int m = 2, n = 3, p = 3, q = 3, i, j;
         int[,] a = {{1, 4, 2}, {2, 5, 1}};
         int[,] b = {{3, 4, 2}, {3, 5, 7}, {1, 2, 1}};
         Console.WriteLine("Matrix a:");
         for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
               Console.Write(a[i, j] + " ");
            }
            Console.WriteLine();
         }
         Console.WriteLine("Matrix b:");
         for (i = 0; i < p; i++) {
            for (j = 0; j < q; j++) {
               Console.Write(b[i, j] + " ");
            }
            Console.WriteLine();
         }
         if(n! = p) {
            Console.WriteLine("Matrix multiplication not possible");
         } else {
            int[,] c = new int[m, q];
            for (i = 0; i < m; i++) {
               for (j = 0; j < q; j++) {
                  c[i, j] = 0;
                  for (int k = 0; k < n; k++) {
                     c[i, j] += a[i, k] * b[k, j];
                  }
               }
            }
            Console.WriteLine("The product of the two matrices is :");
            for (i = 0; i < m; i++) {
               for (j = 0; j < n; j++) {
                  Console.Write(c[i, j] + "\t");
               }
               Console.WriteLine();
            }
         }
      }
   }
}

輸出

上述程式的輸出如下所示。

Matrix a:
1 4 2
2 5 1
Matrix b:
3 4 2
3 5 7
1 2 1
The product of the two matrices is :
172832
223540

現在讓我們來理解一下上述程式。

首先,顯示兩個矩陣a和b。相應的程式碼片段如下所示。

for (i = 0; i < m; i++) {
   for (j = 0; j < n; j++) {
      Console.Write(a[i, j] + " ");
   }
   Console.WriteLine();
}
Console.WriteLine("Matrix b:");
for (i = 0; i < p; i++) {
   for (j = 0; j < q; j++) {
      Console.Write(b[i, j] + " ");
   }
   Console.WriteLine();
}

如果第一個矩陣的列數不等於第二個矩陣的行數,則這兩個矩陣無法相乘,程式會顯示相應的提示資訊。相應的程式碼片段如下所示。

if(n! = p) {
   Console.WriteLine("Matrix multiplication not possible");
}

否則,使用巢狀for迴圈計算矩陣a和b的乘積,即矩陣c。然後顯示矩陣c。相應的程式碼片段如下所示:

for (i = 0; i < m; i++) {
   for (j = 0; j < q; j++) {
      c[i, j] = 0;
      for (int k = 0; k < n; k++) {
         c[i, j] += a[i, k] * b[k, j];
      }
   }
}
Console.WriteLine("The product of the two matrices is :");
for (i = 0; i < m; i++) {
   for (j = 0; j < n; j++) {
      Console.Write(c[i, j] + "\t");
   }
   Console.WriteLine();
}

更新於: 2020年6月26日

10K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.