how to multiply matrix

pflee2002
12-07-2008, 02:23 PM
Hello, folks:
This is my first post. My question is pretty simple. In the framework (data structure) of NR3, how can I do matrix multiplication? I didn't see any code or chapter mentioning that simple operation?
Thanks a lot

davekw7x
12-07-2008, 03:30 PM
...how can I do matrix multiplication...

Yeah, there's an interesting story as to why there is no matrix class in the C++ Standards definitions, and therefore there are no "built-in" matrix operations. Bottom line: NR3 doesn't add anything, and if you don't have access to a third-party matrix class library, you can do it the way that they teach in math class:

#include "../code/nr3.h"

void printmat(MatDoub_I m)
{
for (int i = 0; i < m.nrows(); i++) {
for (int j = 0; j < m.ncols(); j++) {
cout << " " << setw(3) << m[i][j];
}
cout << endl;
}
cout << endl;
}
int main()
{
int i, j, k;
Doub data_a[2*3] = {1, 2, 3, 4, 5, 6};
Doub data_b[3*2] = {6, 5, 4, 3, 2, 1};
MatDoub a(2,3,data_a);
MatDoub b(3,2,data_b);
MatDoub c(2,2);
cout << "Matrix [a]:" << endl;
printmat(a);

cout << "Matrix [b]:" << endl;
printmat(b);

//
// The number of columns in a ***must*** be equal to
// the number of rows in b
//
if (a.ncols() != b.nrows()) {
cout << "Matrix multiplication can not be performed." << endl;
return 0;
}

for (i = 0; i < a.nrows(); i++) {
for (j = 0; j < b.ncols(); j++) {
Doub temp(0.0);
for (k = 0; k < a.ncols(); k++) {
temp += a[i][k]*b[k][j];
}
c[i][j] = temp;
}
}

cout << "The product [a] * [b]:" << endl;
printmat(c);

return 0;
}

Output:

Matrix [a]:
1 2 3
4 5 6

Matrix [b]:
6 5
4 3
2 1

The product [a] * [b]:
20 14
56 41

Regards,

Dave