Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

KernelLink ml;
ml.evaluate(expr);
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

2 Answers 2

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
1  
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+"]]";
         ml.evaluate(expr);
         matrix[i-1]=ml.getIntArray1();
    }

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

    ml.evaluate("{{0,1},{0,0}}");
    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

 
discard

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.