Code Generation for Complex Data

Restrictions When Defining Complex Variables

For code generation, you must set the complexity of variables at the time of assignment, either by assigning a complex constant or using the complex function, as in these examples:

x = 5 + 6i; % x is a complex number by assignment.
y = 7 + 8j; % y is a complex number by assignment.
x = complex(5,6); % x is the complex number 5 + 6i.

Once you set the type and size of a variable, you cannot cast it to another type or size. In the following example, the variable x is defined as complex and stays complex:

x = 1 + 2i; % Defines x as a complex variable.
y = int16(x); % Real and imaginary parts of y are int16.
x = 3; % x now has the value 3 + 0i.

Mismatches can also occur when you assign a real operand the complex result of an operation:

z = 3; % Sets type of z to double (real)
z = 3 + 2i; % ERROR: cannot recast z to complex

As a workaround, set the complexity of the operand to match the result of the operation:

m = complex(3); % Sets m to complex variable of value 3 + 0i
m = 5 + 6.7i; % Assigns a complex result to a complex number

Expressions With Complex Operands Yield Complex Results

In general, expressions that contain one or more complex operands produce a complex result in generated code, even if the value of the result is zero. Consider the following example:

x = 2 + 3i;
y = 2 - 3i;
z = x + y;  % z is 4 + 0i.

In MATLAB®, this code generates the real result z = 4. During code generation, the types for x and y are known, but their values are not. Because either or both operands in this expression are complex, z is defined as a complex variable requiring storage for both a real and an imaginary part. z equals the complex result 4 + 0i in generated code, not 4 as in MATLAB code.

Exceptions to this behavior are:

  • Functions that take complex arguments but produce real results return real values.

    y = real(x); % y is the real part of the complex number x.
    y = imag(x); % y is the real-valued imaginary part of x.
    y = isreal(x); % y is false (0) for a complex number x.
  • Functions that take real arguments but produce complex results return complex values.

    z = complex(x,y); % z is a complex number for a real x and y.
Was this topic helpful?