Monday, October 25, 2010

New Code for Muliplication of two matrices

Here I have given code for multiplication of two matrices.You can check it on your machine and give me reply I alsocreated code for finding inverse of any matrix and will post if you requested it.
public class MultiplyTwoMatrix {
    public static void main(String ar[])
    {
        int matrix1[][],row,column,matrix2[][],a[],result[][],row2,column2;
        java.util.Scanner sc=new  java.util.Scanner(System.in);
    int count=0;
        do{
            if(count>0)
        System.out.println("enter the valid row & column (column1=row2) for multiplication");
            System.out.println("enter the row & column of first matrix");
        row=sc.nextInt();
        column=sc.nextInt();
        System.out.println("enter the  column of second matrix");
        row2=column;
        column2=sc.nextInt();
        count++;
    }while(!(column==row2));
       
       
        matrix1=new int[row][column];
        matrix2=new int[row2][column2];
        result=new int[row][column2];
        a=new int[column];
        int sum=0;
        System.out.println("Enter fist matrix"+row+"x"+column);
        for(int i=0;i<row;i++)
        {
            for(int l=0;l<column;l++)
                matrix1[i][l]=sc.nextInt();
               
        }
        System.out.println("Enter second matrix"+row2+"x"+column2);
        for(int i=0;i<row2;i++)
        {
            for(int l=0;l<column2;l++)
                matrix2[i][l]=sc.nextInt();
        }       
        for(int i=0;i<row;i++)
        {
            for(int l=0;l<column;l++)
                    a[l]=matrix1[i][l];
            for(int j=0;j<column2;j++)
            {
                sum=0;
                for(int l=0;l<column;l++)
                    sum+=a[l]*matrix2[l][j];
                result[i][j]=sum;
            }
        }
        //print output
        for(int i=0;i<row;i++)
        {
            for(int l=0;l<column2;l++)
                System.out.print("\t"+result[i][l]);
            System.out.println();
        }
       
       
    }

}

No comments:

Post a Comment