2 つの行列による行列の乗算
2 つの行列を乗算するには、特定のルールに従う必要があります。まず、最初の行列の列数は、2 番目の行列の行数と等しくなければなりません。2 番目に、結果の行列は、最初の行列と同じ行数と、2 番目の行列と同じ列数を持つことになります。
2 つの行列があるとしましょう。
A = {{1, 3, 5},
{4, 2, 6}};
B = {{7, 4},
{3, 1},
{6, 9}};
これら 2 つの行列を乗算するには、行と列のドット積を行います。行列の要素は、次の式を使って乗算されます。
result[row][col] = matrix1[row][0] * matrix2[0][col]
+ matrix1[row][1] * matrix2[1][col]
+ matrix1[row][2] * matrix2[2][col]
+...;
以下は、行列乗算に関する C プログラムです。
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
// 2 つの行列を定義する
int first[10][10], second[10][10], result[10][10];
// 最初の行列の行数と列数を入力する
printf("Enter the number of rows and columns of the first matrix:\n");
scanf("%d %d", &m, &n);
// 最初の行列の要素を入力する
printf("Enter the %d elements of the first matrix:\n", m * n);
for (c = 0; c < m; c++) {
for (d = 0; d < n; d++) {
scanf("%d", &first[c][d]);
}
}
// 2 番目の行列の行数と列数を入力する
printf("Enter the number of rows and columns of the second matrix:\n");
scanf("%d %d", &p, &q);
// 2 番目の行列の要素を入力する
printf("Enter the %d elements of the second matrix:\n", p * q);
for (c = 0; c < p; c++) {
for (d = 0; d < q; d++) {
scanf("%d", &second[c][d]);
}
}
// 行列を乗算できるかどうかを確認する
if (n!= p) {
printf("Matrices cannot be multiplied with each other.\n");
} else {
// 行列を乗算する
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k] * second[k][d];
}
result[c][d] = sum;
sum = 0;
}
}
// 結果の行列を表示する
printf("The resulting matrix is:\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
printf("%d\t", result[c][d]);
}
printf("\n");
}
}
return 0;
}
このプログラムは、ユーザーに 2 つの行列の要素を入力してもらい、乗算できるかどうかを確認し、可能であれば乗算し、結果の行列を表示します。