Programmer's Toolbox
The matrix reprogrammed
Jack Crenshaw
4/13/2008 6:00 AM EDT
Over the last few issues, we've been talking about the math entity called a matrix. I've given examples of how matrices are useful and how matrix algebra can simplify complicated problems. A messy problem in simultaneous linear equations becomes almost trivial when cast in terms of matrix algebra. And I've shown you that the rules of matrix algebra aren't rules made up by math professors to keep us awake nights, but rather are rules that come naturally from the nature of the problems and their solutions.
Before we can turn the rules of matrix algebra into C++ code, we need to discuss one more topic: how to resolve the mathematical concepts of matrices with the realities of C++ arrays. Before we go there, however, there's one matter of old business I'd like to add.
Pouring over data
When I gave you the rule concerning matrix multiplication, I made no pretense that it was easy or intuitively obvious. On the contrary, I told you that although it seemed crazy, it had to work that way in order to solve problems in linear algebra. I led you through an example of the "two-finger" approach, where you let one finger move along elements of a matrix row and another down a column in the vector it multiplies.
Reader Dean Carpenter wrote to tell me of a mnemonic device that seems to make the matrix-vector product a little more rational. He wrote:
I harken back to my days at school in Sydney, Australia and the calculus classes taught by Mr. Blazey. He had a very simple method:
Take each horizontal row in the matrix and pour it into the vertical vector. Do your multiplies, add them up. The row points to the location in the result vector.
The act of pouring is quite natural, and it's something that has stuck with me all these eons.
I agree wholeheartedly. In Figure 1, I've tried to depict the process. It helps if you think of the numbers in each row of the matrix as floating in some fluid. We can pour the fluid from any row into the vertical container, but the order of elements is preserved.






rj2k000
4/14/2008 3:42 AM EDT
You can tell C about multidimensional arrays in the function header:
static void
matrix(int rows, int cols, double M[rows][cols + 1])
{
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
M[i][j] = 1.0;
}
M[i][cols] = 0.0;
}
}
Sign in to Reply
rj2k000
4/14/2008 3:44 AM EDT
That last comment ate half the square brackets so you'll have to guess where they are.
Sign in to Reply
HJV
4/14/2008 4:00 AM EDT
If I have to handle matrix operations I would'nt go for Fortran, but do it in Python ...
URI: http://numpy.scipy.org
Hans
Sign in to Reply