使用数组的矩阵乘法给了我错误的答案

matrix multiplication using arrays gives me wrong answer

本文关键字:错误 答案 数组      更新时间:2023-10-16

我正在尝试将 3x4 和 4x2 矩阵相乘,然后将 3x2 矩阵输出到屏幕上。出于某种原因,我弄错了最后一行,但前两行是正确的。

我试过改变我的条件

int result[6];
int rows=3;
int columns = 2;
int mvalue=4;

但还是得到了错误的答案。

mvalue应该是矩阵大小的中间值,在本例中为 4(3x 4 ×4x2(。

void multiMatrix(int matrix1[], int matrix2[], int result[], int rows, int columns, int mvalue){
for(int i=0; i<rows; i++){
for(int j=0; j<columns; j++){
result[i*columns+j]=0;
for(int w=0; w<mvalue; w++){
result[i*columns+j]= result[i*columns+j]+matrix1[i*columns+w]*matrix2[w*columns+j];
}
}
}

}
#include <iostream>
int main(){
int matrix1[]={1,2,3,4,
1,2,3,4,
5,4,5,3};
int matrix2[]={1,2,
3,4,
1,2,
3,4};
int result[6];
int rows=3;
int columns = 2;
int mvalue=4;
multiMatrix(matrix1, matrix2, result, rows, columns, mvalue);
for(int i=0; i<rows; i++){
for(int j=0; j<columns; j++){
std::cout<<result[i*rows+j]<<" ";
}
std::cout << std::endl;
}
}

输出应为:

22 32
22 32
31 48

我得到的实际输出是:

22 32
22 32
1  2

计算行应该是这样的:

result[i*columns+j] += matrix1[i*mvalue+w]*matrix2[w*columns+j];

此外,当您打印出值时,您应该打印出来

cout<<result[i*columns+j]<<" ";

而不是

cout<<result[i*rows+j]<<" "; // i * rows is squaring itself

您可以通过执行something * columns + something来索引矩阵 1和矩阵2

这不可能是正确的,因为矩阵 1 和矩阵 2 具有不同的形状。在一种情况下,乘法应为 4,在另一种情况下应乘以 2。

我会让你从那里调试。