Monday, January 27, 2014

Matrix Operation in Java: Addition of two 2x2 matrices demonstrated


For addition or subtraction, the dimensions of the matrices must be same. This is just a demonstration code and can be rewritten in a far more optimized manner.
package com.learning.ds.matrices;

/**
 * Created by Rajdeep on 27/1/14.
 */
public class MatrixAdditionDemo {
    public static void main(String[] args){
        int[][] arr1 = {{1,2,3},{4,2,6}};
        int[][] arr2 = {{10,20,30},{40,50,60}};

        System.out.println("Matrix A:");
        for(int i=0; i < arr1.length; i++){
            for(int j=0; j < arr1[i].length; j++){
                System.out.print(arr1[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("Matrix B:");
        for(int i=0; i < arr2.length; i++){
            for(int j=0; j < arr2[i].length; j++){
                System.out.print(arr2[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("Addition of A and B:");
        int[][] tempArr = addMatrices(arr1,arr2);
        if(tempArr!=null){
            for(int i=0; i < tempArr.length; i++){
                for(int j=0; j < tempArr[i].length; j++){
                    System.out.print(tempArr[i][j] + " ");
                }
                System.out.println();
            }
        }

    }

    //add the matrices
    private static int[][] addMatrices(int[][] m1, int[][] m2){
        //check size
        if(!ofSameSize(m1, m2)){
            System.out.println("[Error] The matrices' dimension in operation do not match!");
            return null;
        }
        int len1 = m1.length;
        int[][] tempArr = new int[2][3];
        for(int i=0; i < tempArr.length; i++){
            for(int j=0; j < tempArr[i].length; j++){
                tempArr[i][j] = m1[i][j] + m2[i][j];
            }
        }
        return tempArr;
    }

    //for adding, the size must be same
    private static boolean ofSameSize(int[][] m1, int[][] m2) {
        int len1 = m1.length;
        int len2 = m2.length;
        boolean check = true;
        if(len1==len2 & len1!=0){
            //System.out.println("length is: " + len1 + " and " + len2);
            for(int i=0; i < len1; i++){
                if(!(m1[i].length == m2[i].length)){
                    check = false;
                }
            }
        }
        else
            check = false;

        return check;
    }
}

Sample output 1:
Matrix A:
1 2 3
4 2 6
Matrix B:
10 20 30
Addition of A and B:
[Error] The matrices' dimension in operation do not match!

Sample output 2:
Matrix A:
1 2 3
4 2 0 
 
Matrix B:
10 20 30
11 5 3 
 
Addition of A and B:
11 22 33
15 7 3 

No comments:

Post a Comment

Liked or hated the post? Leave your words of wisdom! Thank you :)