Main Content

Pass Java Array Arguments to MATLAB

2-D Array Arguments for MATLAB Functions

Some MATLAB® functions accept a 2-D array as a single input argument and use the columns of the array separately. By default, if you pass a 2-D array to a MATLAB from Java®, the array is split into separate arguments along the second dimension. To prevent this issue, cast the 2-D array to Object:

double[][] data = {{1.0, 2.0, 3.0}, {-1.0, -2.0, -3.0}};
HandleObject[] h = eng.feval("plot", (Object) data);

Multidimensional Arrays

MATLAB and Java use different representations to display multidimensional arrays. However, indexing expressions produce the same results. For example, this example code defines an array with three dimensions in MATLAB. The array variable is then passed to Java and the results of indexed references are compared.

import com.mathworks.engine.*;
import java.io.StringWriter;
import java.util.Arrays;

public class ArrayIndexing {
    public static void main(String[] args) throws Exception {
        MatlabEngine eng = MatlabEngine.startMatlab();
        StringWriter writer = new StringWriter();
        eng.eval("A(1:2,1:3,1) = [1,2,3;4,5,6];");
        eng.eval("A(1:2,1:3,2) = [7,8,9;10,11,12]");
        double[][][] A = eng.getVariable("A");
        System.out.println("In Java: \n"+ Arrays.deepToString(A));
        eng.eval("A(1,1,:)",writer,null);
        System.out.println("A(1,1,:) " + writer.toString());
        System.out.println("Java [0][0][0] " + A[0][0][0]);
        System.out.println("Java [0][0][1] " + A[0][0][1]);
    }
}

Here is the program output showing how MATLAB and Java display the arrays. In MATLAB:

A(:,:,1) =

     1     2     3
     4     5     6


A(:,:,2) =

     7     8     9
    10    11    12

In Java: 
[[[1.0, 7.0], [2.0, 8.0], [3.0, 9.0]], [[4.0, 10.0], [5.0, 11.0], [6.0, 12.0]]]

Here are the results showing indexed reference to the first element in each outer dimension:

A(1,1,:) 
ans(:,:,1) =

     1


ans(:,:,2) =

     7


Java [0][0][0] 1.0
Java [0][0][1] 7.0

In MATLAB and Java, the results of the indexed expression are the same.

Related Topics