Friday, 28 June 2013

Java matrix multiplication simple example

Java matrix multiplication simple example

Here is a simple example of Matrix program. Normally Matrix program is bit complex when compared to other programs and we may get confused.
Here we have shared a small matrix program with proper comments.
Please post your doubts if you have :)

package hello;

/**
 *
 * @author surendar
 */
import java.io.*;

class mat //super class
{
int i,j,m=0,n=0;
int a[][]=new int[10][10];
int b[][]=new int[10][10];
int s[][]=new int[10][10];

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

void get() throws IOException //method for getting the values
{
    System.out.println("enter the number of rows and columns");
    m=Integer.parseInt(br.readLine());  //row of first matrix and column of second matrix
    n=Integer.parseInt(br.readLine());   //column of first matrix and row of second matrix
    System.out.println("enter the first "+m+" * "+n+" matrix value");

    for(i=1;i<=m;i++)
    {
        for(j=1;j<=n;j++)
        {
            System.out.println("enter the "+i+"th row "+j+"th column value");
            a[i][j]=Integer.parseInt(br.readLine());//gets the input for first matrix
        }
    }
    System.out.println("enter the second "+n+" * "+m+" matrix value");
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=m;j++)
        {
            System.out.println("enter the "+i+"th row "+j+"th column value");
            b[i][j]=Integer.parseInt(br.readLine());//gets the input for second matrix
        }
    }
}
}

class mul extends mat
{
   
void calc()//function for calculating the matrix multiplication
{int k;
    for(i=1;i<=m;i++)
    {
        for(j=1;j<=m;j++)
        {
            for(k=1;k<=n;k++)
            {
            s[i][j]=s[i][j]+a[i][k]*b[k][j]; //formula to calculate matrix multiplication
            }
        }
    }
 }

void disp()
{
    System.out.println("The solution matrix is:");
    for(i=1;i<=m;i++)
    {
        for(j=1;j<=m;j++)
        {
            System.out.print(s[i][j]+"  ");   // displays the solution matrix
        }
        System.out.println("\n");
       
}

}
}
public class matrix {
    public static void main(String args[]) throws IOException
    {
        mul m=new mul();
        m.get();
        m.calc();
        m.disp();
       
    }
   
}

Hope this example will give you a clear idea about matrix coding in java.

No comments:

Post a Comment