Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block Matrix Multiplication [closed]

Tags:

c++

c

caching

I want to perform a block matrix multiplication(Divide a matirix into multiple sxs matrices and multiply the corresponding blocks). I have written the code as following the sample code of architecture book of Hennesy:

for(int jj=0;jj<=(n/s);jj += s){
            for(int kk=1;kk<=(n/s);kk += s){
                    for(int i=1;i<=(n/s);i++){
                            for(int j = jj; j<=((jj+s-1)>(n/s)?(n/s):(jj+s-1)); j++){
                                    temp = 0;
                                    for(int k = kk; k<=((kk+s-1)>(n/s)?(n/s):(kk+s-1)); k++){
                                            temp += b[i][k]*a[k][j];
                                    }
                                    c[j][i] += temp;
                            }
                    }
            }
    }  

Here, nxn is the size of original matrix. a, b matrices are of same size. I am dividing a,b matrices into blocks of size sxs. In my program, i have given block size to be 4. I put all elements of a, b as 5, a constant and n = 1000. However, i am getting wrong values in my result. Am i doing something wrong here? Stuck on this from past 2 hours. Can you guys please help if possible. The reference code in book is like this:

for (jj = 0; jj <= size; jj += N) {
    for (kk = 1; kk <= size; kk += N) {
        for (i = 1; i <= size; i++) {
            for (j = jj; j <= findMin(jj+N-1, size); j++) {
                temp = 0;
                for (k = kk; k <= findMin(kk+N-1, size); k++) {
                    temp += B[i][k] * A[j][k];
                }
                C[j][i] += temp;
            }
        }
     }
}  

Here, s=N and size = n/s

like image 347
Justin Carrey Avatar asked Apr 20 '13 02:04

Justin Carrey


2 Answers

for(int jj=0;jj<N;jj+= s){
        for(int kk=0;kk<N;kk+= s){
                for(int i=0;i<N;i++){
                        for(int j = jj; j<((jj+s)>N?N:(jj+s)); j++){
                                temp = 0;
                                for(int k = kk; k<((kk+s)>N?N:(kk+s)); k++){
                                        temp += a[i][k]*b[k][j];
                                }
                                c[i][j] += temp;
                        }
                }
        }
}

AxB size is N

like image 80
laxy Avatar answered Oct 16 '22 00:10

laxy


The error is on this line. You have

 temp += b[i][k]*a[k][j];

and you should have

 temp += b[i][k]*a[j][k];

instead.

It would also be nicer if you could put this piece in a function instead of this line:

((jj+s-1)>(n/s)?(n/s):(jj+s-1));
like image 44
Wilmer E. Henao Avatar answered Oct 16 '22 00:10

Wilmer E. Henao