c++ - 使用数组的矩阵乘法给了我错误的答案
问题描述
我正在尝试将 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
解决方案
计算线应该是这样的:
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
推荐阅读
- eclipse - 如何使用 Eclipse DVT 中的命令使 ModelSim 显示波形?
- git - Using git bisect to find the latest commit that doesn't build
- scala - 如何将 ADT 列表分成其变体?
- python-3.x - Python:查找所有长度为 k 且总和为 n 的回文序列
- r - r gganimate (0.9.9.9) 和 transform_polygon 用于雷达图
- javascript - 如何在 Angular 2 中打印 Excel 文件?
- node.js - 使用 top 和 nodeJS 创建时间序列
- python - 是否可以在芹菜中运行包含链的组?
- azure - Azure Functions 代理 - 如果值包含 JSON,则无法设置 HTTP 标头
- sql - 有条件地从 postgresql 中的单独表中选择一列