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.
This example code uses MATLAB functions to:
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(); } }
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(); } }