행렬 곱셈 프로그램은 두 행렬을 곱하는 데 사용됩니다. 이 절차는 첫 번째 행렬의 열 수가 두 번째 행렬의 행 개수와 같은 경우에만 가능합니다.
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
이제 위의 프로그램을 이해합시다.
먼저 두 개의 행렬과 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 루프를 사용하여 행렬과 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();
}