โปรแกรมสำหรับการคูณเมทริกซ์ใช้เพื่อคูณเมทริกซ์สองตัว ขั้นตอนนี้เป็นไปได้ก็ต่อเมื่อจำนวนคอลัมน์ในเมทริกซ์แรกเท่ากับจำนวนแถวในเมทริกซ์ที่สอง
โปรแกรมที่แสดงการคูณเมทริกซ์ใน 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");
} ไม่เช่นนั้น nested for loop จะใช้เพื่อให้ได้ผลคูณของเมทริกซ์ 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();
}