问题描述
enter image description here在此作业中,您需要编写一个程序,该程序读取大小为 n x m 和 s x t 的两个矩阵,然后输出这两个矩阵的乘法结果。由于事先不知道矩阵的大小,因此您需要为矩阵实现动态内存分配方案。您的程序应该提示用户输入 n、m、s、t 和每个矩阵的元素。之后,如果可以对矩阵进行乘法,您的程序应该输出每个矩阵和矩阵乘法的结果。
回想一下,如果矩阵 A 的大小为 n x m,矩阵 B 的大小为 m x t,则生成的矩阵 C 的大小将为 n x t。但是,如果一个矩阵是 n x m,另一个是 s x t,如果 m 不等于 s,这些矩阵就不能相乘。
如果您不熟悉矩阵乘法问题,请研究以下示例,以找到二维矩阵乘法的一般解决方案。在此示例中,矩阵 A 和 B 的大小为 3 x 3。条目 Xij 表示元素 X[i][j]。
A00 A01 A02 B00 B01 B02
A = A10 A11 A12 B = B10 B11 B12
A20 A21 A22 B20 B21 B22
矩阵 A 和 B 的乘法结果等于
A00 * B00 + A01 * B10 + A02 * B20 A00*B01 + A01 * B11 + A02*B21 A00*B02 + A01 *B12 + A02 *B22
C = A10 * B00 + A11 * B10 + A12 * B20 A10B01 + A11 * B11 + A12B21 A10B02 + A11 B12 + A12 B22 A20 * B00 + A21 * B10 + A22 * B20 A20B01 + A21 * B11 + A22B21 A20B02 + A21 *B12 + A22 *B22
要解决这个问题,您需要确定如何从矩阵 A 和 B 的条目中获取条目,例如 C[i][k]。一旦您弄清楚这一点,编程将是一项非常简单的任务。警告;在开始编程之前,请测试您的解决方案。
解决方法
矩阵乘法是通过首先确定结果矩阵的大小来完成的。您只需取第一个矩阵的行数和第二个矩阵的列数。然后将第一个矩阵的每一行与第二个矩阵的每一列相乘。这是代码。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **a,**b,**c;
int n,m,s,t;
int i,j;
printf("\nEnter rows for matrix A: ");
scanf("%d",&n);
printf("\nEnter cols for matrix A : ");
scanf("%d",&m);
printf("\nEnter rows for matrix B : ");
scanf("%d",&s);
printf("\nEnter cols for matrix B: ");
scanf("%d",&t);
if(m != s)
{
printf("\nCan't multiply two matrices if col of a and row of b are not same.");
return(0);
}
a = (int **) malloc(n*sizeof(int *));
b = (int **) malloc(s*sizeof(int *));
c = (int **) malloc(n*sizeof(int *));
for(i=0; i<n; i++)
a[i] = (int *)malloc(m*sizeof(int));
for(i=0; i<s; i++)
b[i] = (int *)malloc(t*sizeof(int));
for(i=0; i<n; i++)
c[i] = (int *)malloc(t*sizeof(int));
printf("\nEnter elements of matrix A :\n");
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
printf("\tA[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\nEnter elements of matrix B :\n");
for(i=0; i<s; i++)
{
for(j=0; j<t; j++)
{
printf("\tB[%d][%d] = ",&b[i][j]);
}
}
printf("Elements of matrix A: \n");
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
printf(" %d ",a[i][j]);
}
printf("\n");
}
printf("Elements of matrix B: \n");
for(i=0; i<s; i++)
{
for(j=0; j<t; j++)
{
printf(" %d ",b[i][j]);
}
printf("\n");
}
for(i=0; i<n; i++)
for(j=0; j<s; j++)
{
c[i][j] = 0;
for(t=0; t<m; t++)
c[i][j] = c[i][j] + a[i][t] * b[t][j];
}
printf("\n\nResultant matrix :");
for(i=0; i<n; i++)
{
printf("\n\t\t\t");
for(j=0; j<t; j++)
printf("%d\t",c[i][j]);
}
return 0;
}
因此,基本上,您对所需的每个矩阵的行和列进行动态分配。然后为它们提供输入,并使用以下公式计算矩阵 C 的值:
c[i][j] = c[i][j] + a[i][t] * b[t][j];