Multiplicación de matrices con dos matrices
Para multiplicar dos matrices, debes seguir ciertas reglas. Primero, el número de columnas de la primera matriz debe ser igual al número de filas de la segunda matriz. Segundo, la matriz resultante tendrá el mismo número de filas que la primera matriz y el mismo número de columnas que la segunda matriz.
Supongamos que tenemos dos matrices:
A = {{1, 3, 5},
{4, 2, 6}};
B = {{7, 4},
{3, 1},
{6, 9}};
Para multiplicar estas dos matrices, realizaremos un producto punto en sus filas y columnas. Los elementos de las matrices se multiplican utilizando la siguiente fórmula:
result[row][col] = matrix1[row][0] * matrix2[0][col]
+ matrix1[row][1] * matrix2[1][col]
+ matrix1[row][2] * matrix2[2][col]
+...;
A continuación, se presenta un programa en C sobre la multiplicación de matrices:
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
// define two matrices
int first[10][10], second[10][10], result[10][10];
// input the number of rows and columns of the first matrix
printf("Enter the number of rows and columns of the first matrix:\n");
scanf("%d %d", &m, &n);
// input the elements of the first matrix
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]);
}
}
// input the number of rows and columns of the second matrix
printf("Enter the number of rows and columns of the second matrix:\n");
scanf("%d %d", &p, &q);
// input the elements of the second matrix
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]);
}
}
// check if matrices can be multiplied
if (n!= p) {
printf("Matrices cannot be multiplied with each other.\n");
} else {
// multiplying the matrices
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;
}
}
// print the resulting matrix
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;
}
El programa pedirá al usuario que ingrese los elementos de dos matrices, comprobará si se pueden multiplicar, las multiplicará si es posible e imprimirá la matriz resultante.