Pages

Wednesday, January 14, 2015

How To Program a Matrix Calculator - (Java)

Hello Readers, Welcome to my blog; today i will explain you how to program a matrix calculator. I was recently working on a matrix calculator app for android so I thought to share my experience with you. 
This is just a basic idea of doing complex operations on a matrix like finding its determinant and inversing the matrix.
I've done it in Java (for Android) but the idea works for all languages and you can easily convert it into another.-

As you all know a matrix is a 2D array which means storing the value in form of a table. I also made a small overview of 2D arrays in last post -
newtonians3d.blogspot.in/2015/01/how-to-use-2d-two-dimensional-arrays-in.html
And also showed how to get its elements and a simple transpose operation Which was like this - 

float[][] matrix = new float[][] {  {1.2, 1.3, 2.0}, {1, 5, 2.1}, {1.5, 5.1, 2.6}  };
float[][] transposedmatrix = new float[3][3];
for(int i = 0; i < integers.length;  i++){
     for(int j = 0; j < integers[0].length; j++){
      transposedmatrix[i][j] = matrix[j][i];
     }
}

1. The Matrix Class - When dealing with many matrices, creating a class for matrix is always appreciable. It also enables us to take Full advantage of OOP (object- oriented programming). So this is how we define the matrix class -

public class matrix {
    private float[][] value;
    public matrix(float[][] cmatrix) {
    matrix = cmatrix;
    }


The method public matrix is the constructer of matrix class. If you don't know the constructer, it's a method which invokes when a object of that class is created and it returns that class. It can also takes arguments which is a 2D array in our class.
The constructer copies the given 2D array to its private variable value(float[][]) which will store the value of matrix's elements.
Now when you want to use this class you can write this -

matrix m1 = new matrix( new float[][]{ {4,5}, {7,6} });
OR
float[][] array = new float[][] ({ {4,5}, {7,6} }); 


2.Matrix Functions - Now so that we have declared our class we need to write functions or methods of this matrix class. Let's start with the easiest one - The Transpose Matrix operation.

 public float[][] transpose (){
        float[][] transposedmatrix = new float[value[0].length][value.length];
        for(int i = 0; i < value.length;  i++){
            for(int j = 0; j < value[0].length; j++){
                transposedmatrix[i][j] = value[j][i];
            }
        }
        return  transposedmatrix;
    }


This code is just fairly easy to understand it just make a new 2D array with rows equals to the columns of main matrix and columns equals to the rows of main matrix then just assign the [j][i] value to [i][j] of new 2D array.

3.The Determinant Function - 
While the determinant of matrix has the most applications in use its also very complex to calculate. The determinant of Matrix is calculated by following steps (in real life, not in programming)
 Step 1 : Suppose we want to calculate the determinant of the following matrix.
               4,  5,  6
               2,  3,  8
               1,  7,  9
         Now you can see there are 9 elements in this matrix.So there are 9 minors for all the 9 elements. To get the determinant. We have to calculate 
       the Minors of all the elements in a columns or all first elements of row.
Now what is the Minor?
It is the determinant of The matrix formed by cutting the current row and column and then finding the determinant of remaining matrix. 
It's difficult to read so let's illustrate it suppose we need to find the minor of first element in first row -
 Now let's cut the rows and columns adjacent to 4

The remaining portion forms a matrix and the determinant of this matrix is known as the minor of 1st element in first row.
now back to programming i Said we need to calculate the minors of either of all columns in first row or of all the 1st element in every row like in this example of 4,5,6 or 4,2,1.





If you still don't understand let's take the example to get remaining matrix of 2nd element in second row.-

The resultend matrix is [[4,6],[1,9]]
 
As the minors we need to calculate are many and all contain a 2D array its good to make class for minors. I don't find a suitable name for class so i named it remainingmatrix (pretty odd name) because it calculate the matrix of remaining elements.

public class remainingmatrix {
    public float[][] valuematrix;
    public remainingmatrix ( float[][] matrix ,int x,int y){

  }
}

This class also stores the result matrix in a 2D array as a property of class. And its constructer takes three arguments ie. one for the matrix itself and other to for the position for which remaining matrix is to be calculated. ex. if we want to calc. the remaining matrix for the above example we would write -

remainingmatrix m1r = new remainingmatrix(new float[][]{{4,5,6},{2,3,8},{1,7,9}} ,0,0)

To find the remaining matrix of first element of first row.
Now the rest of Code -

 public remainingmatrix ( float[][] matrix ,int x,int y){
        int order = matrix.length;

        int order2 = matrix[0].length;
        valuematrix = new float[order-1][order2-1];
        int incx,incy;
        for(int i =0;i<order-1;i++){
            for(int j =0;j<order2-1;j++){
                        if(i >= x){
                    incx = 1;}
                        else {incx =0;}
                    if(j >= y){
                        incy = 1;
                    }
                    else {incy = 0;}
                valuematrix[i][j] = matrix[i+incx][j+incy];
            }
        }
    }



I don't know how this idea came to my mind but it works well. Let me explain this code -
first it creates a new 2D array which is one shorter in length as the result matrix has one less rows and columns.
And then we declare two variable namely incx and incy and then made a nested loop for the newly created array.
Then it checks if the position of minor is less then the current loop position and if it is then inc variable is 0 other than its 1.
So, We completed this class let's move to our determinant which looks like this now - 

 public float determinant (float [][] value){
    int order = value.length;
    float result =0 ;


Notice that we included an argument for matrix that is it because we need to call this function inside this function. 
For that purpose we will use Recursion.
Now what is recursion?
Ans. Recursion is a situation in which one of the statement in a function make a call to the same function in which its present. It may sounds like Infinite loop but just as a loop has a conditional check to take program out of loop a recrusive also have a conditional check to take program out of loop.

We know that to find a determinant of matrix of order 2 is easy and single line code ie.-((value[1][1]*value[0][0]) - (value[0][1]*value[1][0])), so we will continously call the determinant function until the matrix becomes the order of 2 and then calculate the minors in increasing order first for 3, then 4... until the length of real matrix is reached.
Here is it --


  public float determinant (float [][] value){
    int order = value.length;
    float result =0 ;
        if(order==2){
        result =((value[1][1]*value[0][0]) - (value[0][1]*value[1][0]));
        return result;
        }

        else{
            float [] Minors = new float[order];
            for(float i :Minors){
           }
            remainingmatrix[] co_factors = new remainingmatrix[order];
            float inc =0;
            for(int i = 0; i < order -1; i++){
                co_factors[i] = new remainingmatrix(value , 0 ,i);
                Minors[i] = determinant(co_factors[i].valuematrix);
                if(i % 2 ==0){
                result += Minors[i] *value[0][i];
                }
                else {
                result += Minors[i] * value[0][i] * (-1);
                }
            }
            return result;
        }

    }


First it checks if the matrix is of length 2 and if it is return its determinant but if its not It creates an array of minors and remaining matrix(named co_factor) and then calculate its determinant.
After that it adds up the minors. If the position of Minor is odd its subtracted to result and if its even it's added to result. 
If you want to check the code functionality till now. I'am uploading the apk file of my android app that i made while developing it (The UI is not very good but main thing = it works)-
Although my code works for matrix of any length but i've made a limit to not exceed matrix of length 5 beacuse I'am not able to fit the UI in screen.(cause i'am not a UI developer, if someone can help me out with that please help) -
4Shared Link of Apk-


http://www.4shared.com/mobile/XmjpOoWAba/app-release.html

So that's the only first part of tutorial, i will post the second part when i have some time. Please +1 or comment please. I welcome you. Thanks for reading my post.
bye
- NEWTONIANS

No comments:

Post a Comment