0

Hi I am just a beginner in Java programming. I have got this as a small example in my matlab code which i want to convert into Java. I am stuck in taking the inverse of a simple 3x3 matrix. Below is the matlab code.

T = [1,    2,    3;...
     4,    5,    6;...
     7,    8,    9];

invT = inv(T);

Can someone please help in converting this to java. I know it will need to be converted into an array before taking an inverse and I have found out a way to convert it into an array. Just need help with the inverse. Any help will be appreciated.

  • possible duplicate of [Java inverse matrix calculation](http://stackoverflow.com/questions/1992638/java-inverse-matrix-calculation) – Jim Lewis Apr 04 '14 at 00:17

1 Answers1

-1

Use an Object[][] instead of int[][], which is really an array of arrays of ints. Autoboxing will enable a straight forward init:

Object[][] T = new Object[][]{{1,2,3},{4,5,6},{7,8,9}};

Then implement an inverter for Object[] arrays, that will recurse if needed on arrays of arrays.

public static Object[] invert(Object[] array) {
   int length= array.length;
   for(int i=0; i< length/2; i++)  {
      if(length % 2 == 1 && length == 2*i+1 ) array[i] = invert((Object[])array[i]);
      else {
          Object temp = array[i];
          array[i] = array[array.length-1-i] instanceof Object[]
                    ? invert((Object[])array[array.length-1-i]
                    : array[array.length-1-i];

          array[length-1-i] = temp instanceof Object[]
                              ? invert((Object[])temp)
                              : temp;
      }
   }
   return array;
}


...

invert(T);
deanosaur
  • 621
  • 3
  • 5
  • That is not a matrix inverse algorithm. The matrix product of A and inv(A) should yield the identity matrix. Your code just *reverses* the input, which is not at all equivalent to Matlab's inv() function. – Jim Lewis Apr 04 '14 at 18:21