Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to convert a matrix from Mathematica to an int[][] in Java. I use the code below:

KernelLink ml;
int[][] matrix= ml.getIntArray2();

As example: if expr is {{1,0},{0,1}} I get [[1,0,0,1]] instead [[1,0],[0,1]].

What's wrong? Did I misunderstand getIntArray2()?

share|improve this question

You didn't post a working program so it's impossible to see what you are actually doing. I think you will find that getIntArray2() works correctly. Try adding this to your program and you will see the expected output:

System.out.println(matrix.length);  // 2
System.out.println(matrix[0][0]);   // 1
System.out.println(matrix[0][1]);   // 0
System.out.println(matrix[1][0]);   // 0
System.out.println(matrix[1][1]);   // 1
share|improve this answer
I use Eclipse Debugger. I get an ArrayIndexOutOfBoundsException if I write your code. – Marco Nov 25 '13 at 7:58
That's because you haven't shown us your code. I expect the problem is in your creation of the value of the variable expr. But until you show an actual working fragment of code, we can only guess at the problem. – Todd Gayley Nov 25 '13 at 16:57

Problem solved. I used the code below:

    //l= number of cols
    int l= Integer.parseInt(ml.evaluateToOutputForm("Length["+x+"[["+1+"]]"+"]",0));
    //s= number of rows
    int s= Integer.parseInt(ml.evaluateToOutputForm("Length["+x+"]",0));
    int[][] matrix=new int[s][l];
    for (int i=1; i<s+1; i++){
         String expr=x+"[["+i+"]]";

I still don't understand how to use getIntArray2() and why, for example, this code doesn't work.

    int[][] matrix=ml.getIntArray2();
    System.out.println(matrix.length);  // 1
    System.out.println(matrix[0][0]);   // 0
    System.out.println(matrix[0][1]);   // 1
    System.out.println(matrix[1][0]);   //  java.lang.ArrayIndexOutOfBoundsException: 1
    System.out.println(matrix[1][1]);   //  java.lang.ArrayIndexOutOfBoundsException: 1
share|improve this answer
Your problems stem from not calling waitForAnswer(). The "evaluateToXXX" methods return a result, but when you call evaluate(), you must immediately follow it with waitForAnswer() if you are planning to read the answer, or discardAnswer() if you don't plan to read the answer. – Todd Gayley Nov 25 '13 at 20:32
Your answer is useful, now it works correctly! – Marco Nov 25 '13 at 23:01

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.