Transposing index problem

Hi there,

I'm making a simple benchmarking program for matrix multiplication, but I seem to be slightly stuck.

I'm multiplying int arrays (the matrix is in the vector) of size i*i, both are the same size.
I call them matrix A and matrix B.
Now, I finished my naive code and I want to compare its performance to the performance if I transpose matrix B first. However, I seem to have some problems.
Here's my code so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
for(int i = 0; i < size; ++i)
	for(int j = i+1; j < size; ++j)
	   {
	   	int tmp=B[size*i + j];
	   	B[size*i + j]=B[size*j + i];
	   	B[size*j + i]=tmp;
	   }
			
	for (int i = 0; i < size; i++)
	    for (int j = 0; j < size; j++) {
	        C[i + j*size] = 0;
	        for (int k = 0; k < size; k++)
	        {
	            C[i + j*size] += A[i + k*size]*B[i+k]; //this is the line
		}
            }
}


The first for loop does the transposing and that works out perfectly fine.
What doesn't work fine, and I've already spent about two hours trying to figure out, unfortunately, is how to multiply them if matrix B is transposed. In other words, the line with the comment "this is the line" is what does the actual multiplication and I'm having troubles indexing B properly. i+k is really not the solution.

As an example:
If array A: {1 5 2 6} and B: {0 6 7 9} after transposing B would be B:{0 7 6 9}, and finally the solution would be the multiplication of the two matrices AB={35 51 42 66}

Any help will be greatly appreciated.
C_{jk} = A_{jr} B_{rk}
B'_{jk} = B_{kj}
C_{jk}= A_{jr} B'_{kr}


Now suppose that you want to compute the value for C(4,2) (row 4, column 2)
The equation says C_{4,2} = A_{4,r} B'_{2,r}
the repeating index means sum, so the pseudocode
1
2
3
C(4,2) = 0;
for(int r=0; r<size; ++r)
   C(4,2) += A(4,r)*B'(2,r); 


Consider providing a more intuitive interface, so if you try to access the element (j,k) then you simply do
1
2
3
4
5
6
7
int& get(int *matrix, int row, int column){
   return matrix[row*size+column];
}

get(C,j,k) = 0;
for(int r=0; r<size; ++r)
  get(C,j,k) += get(A,j,r) * get(B_trans,k,r);


Edit; I would actually prefer using classes and operator overloading.
Last edited on
Unfortunately that didn't help me much.
Topic archived. No new replies allowed.