Friday, July 31, 2009

I need the source code for multiplying two matrices with three nested loops.?

its better that the code be in C or C++

I need the source code for multiplying two matrices with three nested loops.?
Here is an implementation in C++:





// For the matrix multiplication to work the following must hold:


// M1COLUMNS == M2ROWS


// The resulting matrix has the same rows as m1 and


// the same columns as m2





// You can change the following values as you like


const int M1Rows = 2;


const int M1COLUMNS = 4;


const int M2ROWS = 4;


const int M2COLUMNS = 3;





int resultRows = M1ROWS;


int resultColumns = M2COLUMNS;





int m1[M1Rows][M1COLUMNS];


int m2[M2ROWS][M2COLUMNS];


int result[resultRows][resultColumns];





int sum = 0;





// Here you have to initialize your m1 %26amp; m2 matrices








// Now here is the code to get the result of multiplying two


// matrices using 3 nested loops:





for(int x = 0; x %26lt; M1ROWS; x++)


{





for(int y = 0; y %26lt; resultColumns; y++)


{





for(int z = 0; z %26lt; M1COLUMNS; z++)


{


sum += (m1[x][z] * m2[z][y]);


}





result[x][y] = sum;


sum = 0;





}





}
Reply:Hmmm, this is a very cool one.





but I cant confirm that this is the right matrix, but this is the almost the same, that I used to type in my practical exams.





# include %26lt;stdio.h%26gt;


# include %26lt;conio.h%26gt;





void main()


{


int a[3][3] , b[3][3], c[3][3], i, j,k;


printf("\n enter matrix a 9 values : ");


for(i=0;i%26lt;3;i++)


for(j=0;j%26lt;3;j++)


scanf("%d",%26amp;a[i][i]);





printf("\n enter matrix b 9 values : ");


for(i=0;i%26lt;3;i++)


for(j=0;j%26lt;3;j++)


scanf("%d",%26amp;b[i][j]);





for(i=0;i%26lt;3;i++)


for(j=0;j%26lt;3;j++)


for(k=0;k%26lt;j;k++) // if you get error only this line has to be modified but dont wonder what can come, later ;)


c[i][j]=a[i][k] * b[k][j];





printf("\n multiplication matrix is : \n");


for(i=0;i%26lt;3;i++){


for(j=0;j%26lt;3;j++) {


printf("%d ",c[i][j]);


}


printf("\n");


}


getch();


}





warm regards,


K.A.G.S.





btw its C code


No comments:

Post a Comment