How I will multiply this matrix by using for loop ?

``````#include<iostream>
using namespace std;
void mat_mul_2d(int mat_out_2d[][2], int mat_in1_2d[][2], int mat_in2_2d[][2])
{
mat_out_2d[0][0]=mat_in1_2d[0][0]*mat_in2_2d[0][0]+mat_in1_2d[0][1]*mat_in2_2d[1][0];
mat_out_2d[1][1]=mat_in1_2d[0][0]*mat_in2_2d[0][1]+mat_in1_2d[0][1]*mat_in2_2d[1][1];
mat_out_2d[2][2]=mat_in1_2d[1][0]*mat_in2_2d[0][0]+mat_in1_2d[1][1]*mat_in2_2d[1][0];
mat_out_2d[3][3]=mat_in1_2d[1][0]*mat_in2_2d[0][1]+mat_in1_2d[1][1]*mat_in2_2d[1][1];
}
int main()
{
int mat_in1_2d[2][2] = {{1, 2},{3, 4}};    /
int mat_in2_2d[2][2]={{1,0},{0,1}};
int mat_out_2d[2][2]={{0},{0}};
mat_mul_2d(mat_out_2d,mat_in1_2d,mat_in2_2d);
return 0;
}
``````

All 4 Replies

You need three loops as indicated in the pseudo code listed below..

``````Loop from I = 0  to   I < MAX
Loop from J = 0  to   J < MAX
Loop from K = 0  to   K < MAX
Output[K][I] += FirstArray[K][J] * SecondArray[J][I]
``````

Please can you explain the logic ?
Thankyou

I am using 3X3 arrays for my example. Listed below are the row and column designations for my three arrays

``````  Output                    A                   B
0,0  0,1  0,2        0,0  0,1  0,2         0,0  0,1  0,2
1,0  1,1  1,2   +=   1,0  1,1  1,2    X    1,0  1,1  1,2
2,0  2,1  2,2        2,0  2,1  2,2         2,0  2,1  2,2
``````

MAX is the larger of number of columns or rows. Since number of columns equals the number of rows, MAX equals 3

I've tried to illustrate the logic for matrix multiplication below. I would recommend that you use paper and pencil to continue on with my illustration to completely understand the logic

``````FOR I = 0 to 2 (MAX-1)
FOR J = 0 to 2 (MAX -1)
FOR K = 0 to 2 (MAX-1)
Output[K,I] +=   A[K,J] X B[J,I]

I = 0
J = 0
K = 0
Output[0,0] += A[0,0]  X B[0,0]

I = 0
J = 0
K = 1
Output[1,0] += A[1,0]  X B[0,0]

I = 0
J = 0
K = 2
Output[2,0] += A[2,0]  X B[0,0]

I = 0
J = 1
K = 0
Output[0,0] += A[0,1]  X B[1,0]

I = 0
J = 1
K = 1
Output[1,0] += A[1,1]  X B[1,0]

I = 0
J = 1
K = 2
Output[2,0] += A[2,1]  X B[1,0]

I = 0
J = 2
K = 0
Output[0,0] += A[0,2]  X B[2,0]

I = 0
J = 2
K = 1
Output[1,0] += A[1,2]  X B[2,0]

I = 0
J = 2
K = 2
Output[2,0] += A[2,2]  X B[2,0]
``````

and on and on and on......

Thank you very much bob..i got the logic

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.