简体   繁体   English

C++ 嵌套 for 循环 - 内积 - marix 乘法

[英]C++ nested for loops - inner product - marix multiplication

I have a matrix A with 4 rows and 3 columns and a matrix B with 8 rows and 4 columns.我有一个 4 行 3 列的矩阵 A 和一个 8 行 4 列的矩阵 B。 The coefficiants in the first column of B should denote those rows of A that I want to take for the inner product with the rows of B. B 的第一列中的系数应该表示 A 的那些行,我想作为与 B 的行的内积。

#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;

int main()
{
int ik, il, im;
//A Matrix
vector<vector<int>> A(4, vector<int>(3));
A={ {0, 0, 0}, {1, 1, 0}, {0, 0, 1}, {1, 1, 1} };

//B Matrix
vector<vector<int>> B(8, vector<int>(4));
B={ {1, 0, 0, 0}, {2, 1, 0, 0}, {2, 0, 1, 0}, {2, 1, 1, 0} ,{3, 0, 0, 1}, {4, 1, 0, 1}, {4, 0, 1, 1}, {4, 1, 1, 1} };

vector<int> BZI; 
BZI={{1},{2},{2},{2},{3},{4},{4},{4}};

//calculate inner products
vector<vector<int>> SKP_AB(4, vector<int>(8));
int skp_temp;
for(ik=0; ik<4; ik++)
{
  for(im=0; im<8; im++)
  {
    for(il=0; il<3; il++)
    {
    skp_temp=A[BZI[ik]][il]*B[im][il+1];
    SKP_AB[ik][im]+=skp_temp;
    }
  }
}
//Ausgabe von SKP_AB
cout << "\n" << "#SKP_AB" << "\n";
for(ik=0; ik<4; ++ik)
{
 for(il=0; il<8; ++il)
 {
 cout << setw(2) << SKP_AB[ik][il];
 }
cout << "\n";
}

return 0;
}

In both BZI and the first column of B you used one based row indexing, but C++ uses zero based row indexing.在 BZI 和 B 的第一列中,您都使用了基于行的索引,但 C++ 使用了基于零的行索引。

So you need to compensate, where you had BZI[ik] you needed BZI[ik]-1所以你需要补偿,在你有BZI[ik]你需要BZI[ik]-1

Notice also how hard it was to reach that answer without being told what output you expected (only your program wasn't working) vs. how obvious it was once told what output you expected.还要注意在没有被告知您期望的输出(只有您的程序不起作用)的情况下获得该答案是多么困难,而一旦被告知您期望的输出是多么明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM