Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

11.16. Multiplying Matricies

Problem

You want to perform efficient multiplication of two matricies.

Solution

Example 11-32 shows an implementation of matrix multiplication that can be used with both the dynamic- or fixed-size matrix implementations. This algorithm technically produces the result of the equation A=A+B*C, which is, perhaps surprisingly, an equation more efficiently computed than A=B*C.

Example 11-32. Matrix multiplication

#include "matrix.hpp" // recipe 11.13
#include "kmatrix.hpp" // recipe 11.14
#include <iostream>
#include <cassert>

using namespace std;

template<class M1, class M2, class M3>
void matrixMultiply(const M1& m1, const M2& m2, M3& m3)
{
  assert(m1.cols() == m2.rows());
  assert(m1.rows() == m3.rows());
  assert(m2.cols() == m3.cols());
  for (int i=m1.rows()-1; i >= 0; --i) {
    for (int j=m2.cols()-1; j >= 0; --j) {
      for (int k = m1.cols()-1; k >= 0; --k) {
        m3[i][j] += m1[i][k] * m2[k][j];
      }
    }
  }
}

int main()
{
  matrix<int> m1(2, 1);
  matrix<int> m2(1, 2);
  kmatrix<int, 2, 2> m3;
  m3 = 0;
  m1[0][0] = 1; m1[1][0] = 2;
  m2[0][0] = 3; m2[0][1] = 4;
  matrixMultiply(m1, m2, m3);
  cout << "(" << m3[0][0] << ", " << m3[0][1] << ")" << endl;
  cout << "(" << m3[1][0] << ", " << m3[1][1] << ")" << endl;
}

Example 11-32 produces the following output:

(3, 4)
(6, 8)

Discussion

When multiplying two matricies, the number of columns in the first matrix must be equal to the number of rows in the second matrix. The resulting matrix has the number of rows of the first matrix and the number of columns ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page