Search code examples
javamatlabmatlab-deploymentmatlab-compiler

How to run Matlab compiled Java function?


I have compiled a Matlab script to Java with Matlab compiler SDK. Everything worked fine. Matlab generated a Jar.file and i included it into my Java Project in eclipse. Now my Problem is, the matlab script contains a complex algorithm function. This function can be now called in Java. I need to read 10 csv files with each containing 10.000 rows with 4 columns of data and pass now the same arguments to the java function as i did in matlab.

The way my csv files are: 4 columns, 10.000 rows.

a x y z
1 3 4 5
4 4 5 6
. . . .

readsfirst the data in a seperate function in the variables.Also get length of a.

[a,x,y,z] = readData(['csv\' files(1).name]);
sizeOfa=length(a);

after i call my algorithm function 3 times with different columns and also pass the size of a.

   algorithm(a,x,sizeOfa);
   algorithm(a,y,sizeOfa);
   algorithm(a,z,sizeOfa);

after this the definition of my algorithm comes.

function y= algorithm(x,y,sizeofX)
   do some stuff...
   end

Now my question:

my values read from csv file are stored in Matlab in a 10000*1 Matrix. If i want to call the same function now in Java. What should i pass in to my function? I can read my values a, x, y, z all in seperate arrays. but an array is 1*10000. Can i just pass an array? The readfile function was not compiled to java, i just compiled my algorithm function.


Solution

  • I found two solutions for my problem.

    MATLAB Solution

    My Matlab function used a 10000*1 Array. It is a Matrix like this

    1
    2
    3
    4
    ..
    10000
    

    An Java array passed to compiled function would be different. It looks like this

    1 2 3 4 .. 10000
    

    Now what did to solve this was, i tranponse the arguments passed to my matlab function.

       function y = algorithm(a,z,sizeOfa)
        {
          a=a'; // transpose 
          z=z'; //transpose
           ...
             //your stuff
    
        }
    

    Now if i pass my array into my java function, the array is internally transpose to a matrix.

    EDIT: Better Solution found

    Java Solution

    double[] t;  // your Double Array
    
    int tSize= t.length; // get Size
    
    MWNumericArray result;
    
    result= MWNumericArray.newInstance(new int[]{tSize,1},t,MWClassID.DOUBLE);
    

    Pass result to your function, it is converted to a n*1 Array, where n is the size of your array.