Main Content

Pass Java CellStr to MATLAB

MATLAB Cell Arrays

MATLAB® cell arrays can contain variable-length character vectors in each cell. Some MATLAB functions require cell arrays of character vectors as input arguments. Use the com.mathworks.matlab.types.CellStr class to define a cell array of character vectors in Java®.

The MATLAB engine converts MATLAB cell arrays of character vectors to Java String arrays when passed from MATLAB to Java.

Create CellStr

This example code creates a MATLAB containers.Map instance by passing a CellStr object and a double array as arguments to the MATLAB containers.Map constructor.

Because containers.Map is a MATLAB handle class, define the returned type as a com.mathworks.matlab.types.HandleObject.

The containers.Map keys method returns a MATLAB cellstr with the key names. However, the MatlabEngine feval method returns a String array to Java.

import com.mathworks.engine.*;
import com.mathworks.matlab.types.*;

public class CellArrays {
    public static void main(String[] args) throws Exception {
        MatlabEngine eng = MatlabEngine.startMatlab();
        CellStr keyCellStr = new CellStr(new String[]{"One", "Two", "Three"});
        double[] valueObject = {1.0, 2.0, 3.0};
        HandleObject myMap = eng.feval("containers.Map", keyCellStr, valueObject);
        String[] keysArray = eng.feval("keys", myMap);
        for (String e: keysArray) {
            System.out.println(e);
        }
        eng.close();
    }
}

Related Topics