使用指针将c中的矩阵相乘 [英] Multiplying matrices in c using pointers
本文介绍了使用指针将c中的矩阵相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我输入两个矩阵时,结果矩阵没有显示正确答案,是我的算法错误还是我不应该以这种方式使用指针?请帮忙!
When I input both the matrices, the resultant matrix doesn't show the proper answer, is my algorithm wrong or I am not supposed to use pointers in that way? Please help!
main() {
int a[3][3],b[3][3],c[3][3],*p[3],*q[3],*r[3],j1=0;
// 1st Matrix
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
scanf("%d",&a[i][j]);
}
}
// 2nd matrix
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
scanf("%d",&b[i][j]);
}
}
// Assigning pointers
for(int i=0;i<3;i++) p[i]=&a[i][0];
for(int i=0;i<3;i++) q[i]=&b[i][0];
for(int i=0;i<3;i++) r[i]=&c[i][0];
// Resultant Matrix
for(int i=0;i<3;i++){
*(*(r+i)+j1) = 0;
for(j1=0;j1<3;j1++){
printf("%d\t",*(*(r+i)+j1));
*(*(r+i)+j1) += *(*(p+i)+j1) * *(*(q+j1)+i);
}
j1 = 0;
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
推荐答案
您的循环遍历二维并执行数组 a
和 b
的逐元素乘法与 b
转置.我怀疑您想要执行矩阵乘法而不是逐元素乘法.为此,您需要三个循环:
Your loops iterate through two dimensions and perform an element-wise multiplication of the arrays a
and b
with b
transposed. I suspect you want to perform a matrix multiplication rather than an element-wise multiplication. To do that, you need three loops:
- 两个循环通过
c
的行和列迭代索引i
和j
. - 一个循环通过
a
和b
的公共维度迭代某个变量,比如k
,并对a的乘积求和[i][k]
和b[k][j]
.
- Two loops iterate indices
i
andj
through the rows and columns ofc
. - One loop iterates some variable, say
k
, through the common dimension ofa
andb
and sums the products ofa[i][k]
withb[k][j]
.
这篇关于使用指针将c中的矩阵相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文