Main Content

Pass Variables from Java to MATLAB

Ways to Pass Variables

You can pass Java® variables to MATLAB® using these methods:

  • Pass the variables as function arguments in calls to the MatlabEngine feval and fevalAsync methods. Variables passed as arguments to function calls are not stored in the MATLAB base workspace.

  • Put the variables in the MATLAB base workspace using the MatlabEngine putVariable and putVariableAsync methods.

For information on type conversions, see Java Data Type Conversions.

Pass Function Arguments

This example code passes the coefficients of a polynomial, x2x6, to the MATLAB roots function.

  • Define a double array p to pass as an argument for the MATLAB roots function.

  • Define a double array r to accept the returned values.

import com.mathworks.engine.*;

public class javaPassArg{
    public static void main(String[] args) throws Exception{
        MatlabEngine eng = MatlabEngine.startMatlab();
        double[] p =  {1.0, -1.0, -6.0};
        double[] r = eng.feval("roots", p);
        for (double e: r) {
            System.out.println(e);
        }
        eng.close();
    }
}

Put Variables in the MATLAB Workspace

This example code puts variables in the MATLAB workspace and uses those variables as arguments in a MATLAB call to the MATLAB complex function. The MATLAB who command lists the workspace variables.

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

public class javaPutVar {
    public static void main(String[] args) throws Exception {
        MatlabEngine eng = MatlabEngine.startMatlab();
        eng.putVariable("x", 7.0);
        eng.putVariable("y", 3.0);
        eng.eval("z = complex(x, y);");
        String[] w = eng.feval("who");
        System.out.println("MATLAB workspace variables " + Arrays.toString(w));
        eng.close();
    }
}

Related Topics