Archive for August 3rd, 2010

Sometimes programing can be fun. Sometimes it isn’t. I particularly hate debugging.

Today I was programming a function that would compute the commutator of two square matrices in c++, which do not have a definite size in the program. I ended up implementing it in the following way, by using the pointers to the beginning of the matrices and the size of the matrix n.

void commutator(int n , double *a1, doubleĀ  *a2, double *b1)
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
for(int k=0; k<n;k++){
*(b1+i+n*j)+= *(a2+i+n*k)*(*(a1+k+j*n))-*(a1+i+n*k)*(*(a2+k+j*n)) ;

The two matrices are a1, a2, and the result is placed on b1.

The placing of parenthesis is very crucial. This was the best solution I found after trying all kinds of other ways that were giving me trouble with the compiler. This is probably good for numerics, but lousy for preventing errors in the handling if one does not pay attention. What is fascinating to me is that the symbol * does two things: both multiplication and looking up the address of a pointer. And these can appear consecutive to one another.

Oh well. Just thought I’d share my messy code.


Read Full Post »