Search code examples
javaarraysmatlabmatlab-deployment

Convert Object[] result in Matlab Runtime to double[][] array Java


How do I convert Object[] result in Matlab Runtime to double[][] array Java? I've tried with "toDoubleArray" like this:

MWNumericArray data1=null;
        MWNumericArray data2=null;
        Object[] result = null;
        Class1 lse = null;
        Object[] hasil;
        try {
            data1=new MWNumericArray(A, MWClassID.DOUBLE);
            data2=new MWNumericArray(target, MWClassID.DOUBLE);
            lse = new Class1();
            result = lse.rekursif_lse(1, data1,data2);
            System.out.println(" "+result[0]);
            MWNumericArray mytemp = (MWNumericArray) result[0];
            double[][] bar =(double[][]) mytemp.toDoubleArray();
            T = bar;
            for(i=0;i<=20;i++){
            for(j=0;j<2;j++){
                System.out.println(" "+T[i][j]);
            }
        }
        }catch (Exception e) {
        System.out.println("Exception! "+e.toString());}
        finally
        {
         MWArray.disposeArray(data1);
         MWArray.disposeArray(data2);
         MWArray.disposeArray(result);
         lse.dispose();
        }

but the output was:

**> In rekursif_lse (line 11)

1.0e+45 *

-0.2047

-0.7003

-0.2422

0.4113

-5.6423

4.5718

-1.6527

3.5924

6.5032

-5.7239

0.2034

0.6966

0.2437

-0.4095

5.6115

-4.5425

1.6626

-3.5839

-6.4737

5.4594

2.0467650070969492E44

Exception! java.lang.ArrayIndexOutOfBoundsException: 1

It can be seen that the Matlab Compiler Runtime is worked but I can't input the "result" to "T" which:

double T[][]=new double[20][1];

How do I solve this?


Solution

  • You're confusing the array indexes: you have a two dimensional array with the measurements [20][1], but in the print loop you've put:

     for(i=0;i<=20;i++){
         for(j=0;j<2;j++){
              System.out.println(" "+T[i][j]);
         }
     }
    

    Which means you're traversing an array of dimensions [20][2]. In order to not go beyond the dimensions of your array, simply remove the for loop for J:

    for(i=0;i<=20;i++){
        System.out.println(" "+T[i][0]);
    }
    

    Because the two dimensional array has in fact one dimension and contains 20 elements - the second coordinate is always 0.