For learning matrix addition you must study my blog about two dimensional array.
In last tutorial we learn how to declare two dimensional array. Here i gave you concept how to add two matrix.
first matrix is
int m1[3][3];
second matrix is
int m2[3][3];
Third matrix is
int m3[3][3];
m3 m1 m2
col0 col1 col2 col0 col1 col2 col0 col1 col2
row0 --- --- --- row0 --- --- --- row0 --- --- ---
row1 --- --- --- row1 --- --- --- row1 --- --- ---
row2 --- --- --- row2 --- --- --- row2 --- --- ---
-------------------------------------------------------------------------------------------------------------------------------
from above scenario
(0,0) of m1 always add (0,0) of m2 and stores in (0,0) of m3
so in c language
m3[0][0]=m1[0][0]+m2[0][0]
similarly
(0,1) of m1 always add (0,1) of m2 and stores in (0,1) of m3
m3[0][1]=m1[0][1]+m2[0][1]
similarly
(0,2) of m1 always add (0,2) of m2 and stores in (0,2) of m3
m3[0][2]=m1[0][2]+m2[0][2]
here we notice that row is constant means 0 but column varies 0,1,2
so for(col=0;col<3;col++)
{
m3[0][col]=m1[0][col]+m2[0][col] ]
}
-------------------------------------------------------------------------------------------------------------------------------
second row of matrix
(1,0) of m1 always add (1,0) of m2 and stores in (1,0) of m3
so in c language
m3[1][0]=m1[1][0]+m2[1][0]
similarly
(1,1) of m1 always add (1,1) of m2 and stores in (1,1) of m3
m3[1][1]=m1[1][1]+m2[1][1]
similarly
(1,2) of m1 always add (1,2) of m2 and stores in (1,2) of m3
m3[1][2]=m1[1][2]+m2[1][2]
here we notice that row is constant means 1 but column varies 0,1,2
so for(col=0;col<3;col++)
{
m3[1][col]=m1[1][col]+m2[1][col] ]
}
-------------------------------------------------------------------------------------------------------------------------------
(2,0) of m1 always add (2,0) of m2 and stores in (2,0) of m3
so in c language
m3[2][0]=m1[2][0]+m2[2][0]
similarly
(2,1) of m1 always add (2,1) of m2 and stores in (2,1) of m3
m3[2][1]=m1[2][1]+m2[2][1]
similarly
(2,2) of m1 always add (2,2) of m2 and stores in (2,2) of m3
m3[2][2]=m1[2][2]+m2[2][2]
here we notice that row is constant means 2 but column varies 0,1,2
so for(col=0;col<3;col++)
{
m3[2][col]=m1[2][col]+m2[2][col] ]
}
-------------------------------------------------------------------------------------------------------------------------------
anyone got idea what i want to say. Yes Here we repeating similar loop row 0, row 1
row2 . We have some way to reduce this task . How it is possible.
Solution :
using second loop out side the column .
for(row=0;row<3;row++)
{
for(col=0;col<3;col++)
{
m3[row][col]=m1[row][col]+m2[row][col] ]
}
}
row2 . We have some way to reduce this task . How it is possible.
Solution :
using second loop out side the column .
for(row=0;row<3;row++)
{
for(col=0;col<3;col++)
{
m3[row][col]=m1[row][col]+m2[row][col] ]
}
}
No comments:
Post a Comment