Wednesday, 2 January 2013

Java Matrix Multiplication (JMM)

Often in many areas of programming people require a tool which can simplify there n*n matrix multiplication problem in reasonable amount of time.

This can usually be done with 3 tight for loop and special care for handling dimension errors(which i assumes most of you knows) to do this i have a designed a special class and added it to my Utilities framework 1.1.2

Lets quickly take 1 example for 2*2 matrix multiplication using Utilities-1.1.2

  
class MatrixMultiplication
{
public static void main(String[] str) throws DimensionError{
        double[][] a = { {1.2,2.25}, {25.0,28.2} };
        double[][] b = { {1.2,2.25}, {25.0,25.2} };
        double[][] multiplyMatrix = new Math().multiplyMatrix(a, b);
        for (double[] ds : multiplyMatrix) {
            for (double d : ds) {
                System.out.print( d + " ");
            }
            System.out.println();
        }
    }
}
}
Output


So, now you know how simple is matrix multiplication.

Dimension Errors

A special care has been taken to indicate that matrix multiplication is not possible and this is indicated using DimensionError Exception

consider the following example

import math.DimensionError;
import math.Math;
public class MatrixMultiplication {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] str) {
        double[][] a = { {1.2,2.25,2}, {25.0,28.2,2}, {25.2, 14.25,2} };
        double[][] b = { {1.2,2.25}, {25.0,25.2} };
 try{
        double[][] multiplyMatrix = new Math().multiplyMatrix(a, b);
        for (double[] ds : multiplyMatrix) {
            for (double d : ds) {
                System.out.print( d + " ");
            }
            System.out.println();
        }
 }catch(DimensionError ex){
  System.out.println(ex.getErrorMessage());
 }
    }
}

Output


Speed


Worst case time complexity is O(n^3)


Download