Block Matrix Multiplication (C Language) Write a matrix multiplication program t
ID: 3685215 • Letter: B
Question
Block Matrix Multiplication (C Language)
Write a matrix multiplication program to multiple two N x N matrices using the block matrix multiplication algorithm shown below:
Each slave is given s rows and s columns. Pairs of s x s submatrices are multiplied and the results added together to produce an s x s submatrix answer.
Choose N = 8 and s = 2. With s = 2, there are 16 submatrices and 16 tasks (T = 16). Test your program with four processes. Make sure the parallel code gives the same answers as the sequential code.
Explanation / Answer
#include<stdio.h>
int main(){
int i,j,k,m,n=8,s=2,res[8][8],temp=0;
//declaring array
int matrixA[8][8] = {
{1,2,3,4,5,6,7,8},
{5,6,7,8,1,2,3,4},
{1,2,3,4,5,6,7,8},
{5,6,7,8,1,2,3,4},
{1,2,3,4,5,6,7,8},
{5,6,7,8,1,2,3,4},
{1,2,3,4,5,6,7,8},
{5,6,7,8,1,2,3,4}
};
int matrixB[8][8] = {
{1,2,3,4,5,6,7,8},
{5,6,7,8,1,2,3,4},
{1,2,3,4,5,6,7,8},
{5,6,7,8,1,2,3,4},
{1,2,3,4,5,6,7,8},
{5,6,7,8,1,2,3,4},
{1,2,3,4,5,6,7,8},
{5,6,7,8,1,2,3,4}
};
//printing initialised matrix
printf(" Matrix A: ");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d ",matrixA[i][j]);
}
printf(" ");
}
printf(" Matrix B: ");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d ",matrixB[i][j]);
}
printf(" ");
}
//matrix block multiplication
for( j=0;j<n;j+= s){
for( k=0;k<n;k+= s){
for( i=0;i<n;i++){
for(m = j; m<((j+s)>n?n:(j+s)); m++){
temp = 0;
for(k = k; k<((k+s)>n?n:(k+s)); k++){
temp += matrixA[i][k]*matrixB[k][m];
}
res[i][j] += temp;
}
}
}
}
printf(" Resultant Matrix: ");
//printing resultant matrix
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d ",res[i][j]);
}
printf(" ");
}
return 0;
}