+ 2

I need help

I was solving a problem to find the product of two matrix I am having a problem understanding the last part of it. I want to know why k was used hear for(i = 0; i < r1; ++i) for(j = 0; j < c2; ++j) for(k = 0; k < c1; ++k) { mult[i][j] += a[i][k] * b[k][j]; } And why This is used hear cout << " " << mult[i][j]; if(j == c2-1) cout << endl; After the for loop of the resultant matrix

9th Feb 2018, 3:31 PM
Dipankar Verma
Dipankar Verma - avatar
6 Respuestas
+ 2
k specifies number of additions to be performed during calculation of single element in resultant matrix .And last if is applied to print the final matrix in proper format that is printing each row in single line and for each next row cursor will move to next line.
9th Feb 2018, 9:25 PM
Ambika Arora
Ambika Arora - avatar
+ 2
Consider you have 2 matrices A= {2 2 3 1 2 2} B={1 2 2 3 1 2} Now A is 2X3 matrix and B is 3X2 matrix and AB will be of 2X2 matrix now the first element of AB will be 2*1+2*2+3*1 now if you carefully notice that for calculating single element of AB we have to perform 3 multiplications and add them.That's why last loop runs 3 times as we have to perform 3 multiplications and add them to get single element of AB.Similar thing can be noticed by taking any example of matrices. And you can print the AB matrix in the following way : for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { cout<<M[i][j]<<"\t"; } cout<<endl; } Hope it clears your both of the queries.Still if there is any doubt you can ask.I will be happy to help.Happy Coding:)
10th Feb 2018, 11:41 AM
Ambika Arora
Ambika Arora - avatar
+ 2
According to me there is no need to put if condition after resultant matrix ,you can silmply print resultant matrix in the way in which i have written previous answer.
10th Feb 2018, 11:46 AM
Ambika Arora
Ambika Arora - avatar
+ 1
Hmmm thx for the help but in the example we are using 2 loops to output the matrix in most case we do apply the same concept but hear in this loop for(i = 0; i < r1; ++i) for(j = 0; j < c2; ++j) for(k = 0; k < c1; ++k) { mult[i][j] += a[i][k] * b[k][j]; } One extra loop is used and i am not able to find why its used and { mult[i][j] += a[i][k] * b[k][j]; } a[i][k]is used instead of a[i][j]
11th Feb 2018, 2:17 AM
Dipankar Verma
Dipankar Verma - avatar
+ 1
Third loop is used to get element value of resultant matrix because in matrix multiplication you have to perform a11*b11+a12*b21+a13*b31 to get first element of product matrix . Similarly other elements of product matrix can be calculated by applying loop.
11th Feb 2018, 8:26 PM
Ambika Arora
Ambika Arora - avatar
0
Second part got cleared can u plz explain me first part more elaborate thx for the help
10th Feb 2018, 1:16 AM
Dipankar Verma
Dipankar Verma - avatar