Saturday, 22 September 2012

Matrix Operation In Java


/******* Java Implementation of Matrix Operation Using Arrays *******/

class Matrix
{
public static void main(String args[])
{
int i,j,k;
int mat1 [][]={ {10,11,12}, {13,14,15}, {16,17,18} };
int mat2 [][]={ {1,2,3}, {4,5,6}, {7,8,9} };
System.out.println("Operation ON Matrices \n1.Addition \n");
int sum [][] = new int [3][3];
for(i=0;i <3;i++)
{
for(j=0;j< 3;j++)
{
sum[i][j] = mat1[i][j] + mat2[i][j];
System.out.print("\t" + sum[i][j]);
}
System.out.println("\t");
}

System.out.println("2.Subtraction\n");
int diff[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
diff [i][j] = mat1[i][j] - mat2[i][j];
System.out.print("\t"+ diff[i][j]);
}
System.out.println("\t");
}

System.out.println("3.Multiplication\n");
int prod[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
prod[i][j] = 0;
{
for(k=0;k< 3;k++)
prod[i][j] = prod[i][j]+mat1[i][k]*mat2[k][j];
}
System.out.print("\t"+ prod[i][j]);
}
System.out.println("\t");

}
}
}

/************* OUTPUT ***************

Operation ON Matrices
1.Addition

11 13 15
17 19 21
23 25 27
2.Subtraction

9 9 9
9 9 9
9 9 9
3.Multiplication

138 171 204
174 216 258
210 261 312 */

0 comments:

Post a Comment