首页 > 解决方案 > 使用数组的矩阵乘法给了我错误的答案

问题描述

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

我试过改变我的条件

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

但仍然得到错误的答案。

mvalue应该是矩阵大小的中间值,在这种情况下为 4 (3x 4 × 4 x2)。

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

标签: c++arraysmatrixmatrix-multiplication

解决方案


计算线应该是这样的:

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

推荐阅读