+ 4
How to Multiply 2 Martices using Cpp. What is logic ?
I am finding it difficult to create a cpp program that can multiply as many number of matrices as many user wants with desired rows and columns, any help will be appreciated.
4 Answers
+ 2
Thanks for advice, ill do more research on it
0
First I would look at how you multiply two matrices by hand. Look at the pattern it has and try to convert it over to an algorithm.
For example
|4 5.| | 5 2|
|1 2.| | 3. 4|
The first element of the new matrix C will be (4 Ă 5) + (5 Ă 3), or (A [0][0] Ă B [0][0]) + (A [0][1] * B [1][0]).
Now look at the rest of the multiplications (I'll leave that to you, check online on matrix multiplication if you get stuck). NOTE, only certain matrices can be multiplied as well, for example a 1x3 and a 1Ă3 cannot be multiplied but a 1Ă3 and a 3Ă1 can. If the columns of matrix one and the rows of matrix two are the same then you can do it.
0
To multiply an mĂn matrix by an nĂp matrix, the n must be the same, and the result is an mĂp matrix.
The time complexity of this c program is O(n3).
For Example: If we multiply a 2Ă4 matrix and a 4Ă3 matrix, then the product matrix will be a 2Ă3 matrix.
Here is the code snippet to multiply two matrices.
/* Multiply both matrices */
for(i = 0; i < rows1; i++){
for(j = 0; j < rows2; j++){
for(k = 0; k < cols2; k++){
productMatrix[i][j] += firstMatrix[i][k]*secondMatrix[k][j];
}
}
}
You can check full c/C++ program here
http://www.techcrashcourse.com/2015/03/c-program-for-matrix-multiplication.html
http://www.techcrashcourse.com/2017/01/cpp-program-to-multiply-two-matrices.html