矩阵乘法_矩阵

 

矩阵乘法_i++_02

用C++实现:

// g++ multiply.cpp -Wall -std=c++11
#include <iostream>
#include <vector>
#include <iomanip>

using std::vector;
using std::cout;
using std::setw;

vector< vector<int> > multiply(vector< vector<int> >m1, vector< vector<int> >m2) {
  if (m1[0].size() != m2.size()) {
    throw "m1 columns count should equal m2 rows count";
  }
  // init
  vector< vector<int> > res(m1.size(), vector<int>(m2[0].size(), 0));
  for (size_t i = 0; i < m1.size(); i++) {
    for (size_t j = 0; j < m2[0].size(); j++) {
      for (size_t k = 0; k < m2.size(); k++) {
	res[i][j] += m1[i][k] * m2[k][j];
      }
    }
  }
  return res;
}

int main(int argc, char *argv[]) {
  vector< vector<int> >a = {
    {1,0,3,-1},
    {2,1,0,2}
  };
  vector< vector<int> >b = {
    {4,1,0},
    {-1,1,3},
    {2,0,1},
    {1,3,4}
  };

  vector< vector<int> >c = multiply(a, b);
  for (size_t i = 0; i < c.size(); i++) {
    for (size_t j = 0; j < c[i].size(); j++) {
      cout << setw(3) << c[i][j];
    }
    cout << "\n";
  }
  return 0;
}

g++ multiply.cpp -Wall -std=c++11

./a.out

  9 -2 -1
  9  9 11