DAPPLE Example: matmul2
Source code:
// @TITLE "matmul2.cc -- matrix multiply"
//
// matmul2 -- a parallel matrix-matrix multiply program
// written using the Data-Parallel Programming Library for Education (DAPPLE)
//
// This version does the classic systolic matrix-matrix multiply;
// that is, it skews each of the input matrices, and then rotates them
// around, doing elementwise multiplies, accumulating in the result.
//
// David Kotz 1994
// $Id: matmul2.cc,v 1.3 94/09/29 12:18:09 dfk Exp Locker: dfk $
#include
#include
#include
#include "dapple.h"
// we'll multiply an NxN matrix by a NxN matrix to get a NxN matrix
const int N = 3;
const intVector VP(N, Identity);
int
main(int argc, char **argv)
{
// we'll compute C = A * B
intMatrix A(N,N);
intMatrix B(N,N);
intMatrix C(N,N);
intMatrix D(N,N); // D is what C should be
// load matrices; row-major order, whitespace-separated integers
cout << "To multiply C = A * B." << endl;
cout << "Enter " << N << " by " << N << " matrix A: " << endl;
cin >> A;
cout << "Enter " << N << " by " << N << " matrix B: " << endl;
cin >> B;
// skew the input matrices. Note that each row or column is
// skewed by a different amount, depending on VP.
A = rotate_rows(A, -VP);
B = rotate_cols(B, -VP);
C = 0; // initialize C
// loop through the rotations
for (int i = 0; i < N; i++) {
C += A * B; // elementwise multiply and accumulate
A = rotate_rows(A, -1);
B = rotate_cols(B, -1);
}
cout << "Result C = " << endl;
cout << C;
cout << "Enter correct " << N << " by " << N << " matrix D: " << endl;
cin >> D;
if (any(C != D))
cout << "The answers are different." << endl;
else
cout << "The answers are the same!" << endl;
return(0);
}
Demonstration:
cat matmul.data
5 -3 1
2 1 4
3 -1 2
2 -1 1
0 1 2
1 0 1
11 -8 0
8 -1 8
8 -4 3
matmul2 < matmul.data
To multiply C = A * B.
Enter 3 by 3 matrix A:
Enter 3 by 3 matrix B:
Result C =
11 -8 0
8 -1 8
8 -4 3
Enter correct 3 by 3 matrix D:
The answers are the same!