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(); }
广告