Main Content

Incorrect Java Data Types

Java String to MATLAB Character Vector

Struct of Character Vectors

Some MATLAB® functions accept a struct of name-value pairs as input arguments. The MATLAB Engine API for Java® provides the com.mathworks.matlab.engine.Struct class to create this data structure in Java and pass it to MATLAB, where it is converted to a MATLAB struct.

Some MATLAB functions that accept struct input require field values to be MATLAB character vectors (char) instead of MATLAB strings (string). To create a Java Struct with the correct type of values, convert from String to char array before passing the variable to MATLAB.

You can use the toCharArray method for the conversion:

char[] on = "on".toCharArray();
char[] yOut = "yOut".toCharArray();
char[] tOut = "tOut".toCharArray();
Struct simParam = new Struct("SaveOutput", on, "OutputSaveName",
        yOut,"SaveTime", on, "TimeSaveName", tOut);

String Argument to Character Vector

When MATLAB functions require char inputs, you can convert the Java String in the function call passed to MATLAB. For example, the MATLAB eval function requires char input:

double result = engine.feval("eval", "3+5");
Undefined function 'eval' for input arguments of type 'string'..

Passing a char array works correctly.

double result = engine.feval("eval", "3+5".toCharArray());

Setting Graphics Object Properties from Java

You can set the values of MATLAB graphics object properties using the handle of the object. Pass the property names and property values as Java char arrays when passing to MATLAB functions.

double[][] data = {{1.0, 2.0, 3.0}, {-1.0, -2.0, -3.0}};
HandleObject[] h = eng.feval("plot", (Object)data);
String property = ("HitTest");
String value = ("off");
eng.feval(0,"set", h, property.toCharArray(), value.toCharArray());

Java Integer to MATLAB double

Some MATLAB functions, such as sqrt restrict the input to double or single precision values. The MATLAB engine converts Java integers to MATLAB int32 values. For MATLAB functions that do not accept integer values, ensure that you pass appropriate numeric values.

double result = engine.feval("sqrt", 4);
Undefined function 'sqrt' for input arguments of type 'int32'.

Passing a double works correctly.

double result = engine.feval("sqrt", 4.0);

Related Topics