Main Content

Pass Variables from MATLAB to Java

Use the MatlabEngine getVariable or getVariableAsync methods to get variables from the MATLAB® base workspace. To determine the appropriate mapping of MATLAB type to Java® type, see Java Data Type Conversions.

Coordinate Conversion

This example code uses the MATLAB cart2sph function to convert from Cartesian to spherical coordinates. The getVariable method gets the returned spherical coordinate variables from the MATLAB base workspace.

import com.mathworks.engine.*;

public class GetPolar {
    public static void main(String[] args) throws Exception {
        MatlabEngine eng = MatlabEngine.startMatlab();
        eng.eval("[az,el,r] = cart2sph(5, 7, 3);");
        double az = eng.getVariable("az");
        double el = eng.getVariable("el");
        double r = eng.getVariable("r");
        System.out.println("Azimuth: " + az);
        System.out.println("Elevation: " + el);
        System.out.println("Radius " + r);
        eng.close();
    }
}

Related Topics