Main Content

Using Complex Variables in Java

Complex Variables in MATLAB

MATLAB® numeric types can represent complex numbers. The MATLAB Engine API supports complex variables in Java® using the com.mathworks.matlab.types.Complex class. Using this class, you can:

  • Create complex variables in Java and pass these variables to MATLAB.

  • Get complex variables from the MATLAB base workspace.

MATLAB always uses double precision values for the real and imaginary parts of complex numbers.

Get Complex Variables from MATLAB

This example code uses MATLAB functions to:

  • Find the roots of a polynomial (roots)

  • Find the complex conjugate of the complex roots (conj)

  • Find the real result of multiplying the complex number array by its conjugate.

Use the getVariable method to return the complex variables to Java.

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

public class javaGetVar {
    public static void main(String[] args) throws Exception {
        MatlabEngine eng = MatlabEngine.startMatlab();
        eng.eval("z = roots([1.0, -1.0, 6.0]);");
        eng.eval("zc = conj(z);");
        eng.eval("rat = z.*zc;");
        Complex[] z = eng.getVariable("z");
        Complex[] zc = eng.getVariable("zc");
        double[] rat = eng.getVariable("rat");
        for (Complex e: z) {
            System.out.println(e);
        }
        for (Complex e: zc) {
            System.out.println(e);
        }
        for (double e: rat) {
            System.out.println(e);
        }
        eng.close();
    }
}

Pass Complex Variable to MATLAB Function

This example code creates a com.mathworks.matlab.types.Complex variable in Java and passes it to the MATLAB real function. This function returns the real part of the complex number. The value returned by MATLAB is of type double even though the original variable created in Java is an int.

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

public class javaComplexVar {
    public static void main(String[] args) throws Exception {
        MatlabEngine eng = MatlabEngine.startMatlab();
        int r = 8;
        int i = 3;
        Complex c = new Complex(r, i);
        double real = eng.feval("real", c);
        eng.close();
    }
}

Related Topics