Code Generation for Complex Data - MATLAB & Simulink (original) (raw)

Restrictions When Defining Complex Variables

For code generation, you must set the complexity of variables at the time of assignment. Assign a complex constant to the variable or use the complex function. For example:

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

After assignment, you cannot change the complexity of a variable. Code generation for the following function fails because x(k) = 3 + 4i changes the complexity of x.

function x = test1( ) x = zeros(3,3); % x is real for k = 1:numel(x) x(k) = 3 + 4i; end end

To resolve this issue, assign a complex constant tox.

function x = test1( ) x = zeros(3,3)+ 0i; %x is complex for k = 1:numel(x) x(k) = 3 + 4i; end end

Code Generation for Complex Data with Zero-Valued Imaginary Parts

For code generation, complex data that has all zero-valued imaginary parts remains complex. This data does not become real. This behavior has the following implications:

Functions That Sort Complex Values by Absolute Value

Functions that sort complex values by absolute value includesort, issorted,sortrows, median,min, and max. These functions sort complex numbers by absolute value even when the imaginary parts are zero. In general, sorting the absolute values produces a different result than sorting the real parts. Therefore, when inputs to these functions are complex with zero-valued imaginary parts in generated code, but real in MATLAB, the generated code can produce different results than MATLAB. In the following examples, the input to sort is real in MATLAB, but complex with zero-valued imaginary parts in the generated code:

Inputs and Outputs for MEX Functions Generated for Complex Arguments

For MEX functions created by the codegen command, the fiaccel (Fixed-Point Designer) command, or theMATLAB Coderâ„¢ app:

Results of Expressions That Have Complex Operands

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 line of code:

Suppose that at run time, x has the value 2 + 3i and y has the value 2 - 3i. In MATLAB, this code produces the real result z = 4. During code generation, the types for x andy are known, but their values are not known. Because either or both operands in this expression are complex, z is defined as a complex variable requiring storage for 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:

Results of Complex Multiplication with Nonfinite Values

When an operand of a complex multiplication contains a nonfinite value, the generated code might produce a different result than the result that MATLAB produces. The difference is due to the way that code generation defines complex multiplication. For code generation: