Differences Between Generated Code and MATLAB Code

To convert MATLAB® code to efficient C/C++ code, the code generator introduces optimizations that intentionally cause the generated code to behave differently, and sometimes produce different results, than the original source code.

Here are some of the differences:

Loop Index Overflow

Suppose that a for-loop end value is equal to or close to the maximum or minimum value for the loop index data type. In the generated code, the last increment or decrement of the loop index might cause the index variable to overflow. The index overflow might result in an infinite loop.

When memory integrity checks are enabled, if the code generator detects that the loop index might overflow, it reports an error. The software error checking is conservative. It might incorrectly report a loop index overflow. By default, memory-integrity checks are enabled for MEX code and disabled for standalone C/C++ code. See Why Test MEX Functions in MATLAB? (MATLAB Coder) and Run-Time Error Detection and Reporting in Standalone C/C++ Code (MATLAB Coder).

To avoid a loop index overflow, use the workarounds in this table.

Loop Conditions Causing the Potential OverflowWorkaround
  • The loop index increments by 1.

  • The end value equals the maximum value of the integer type.

If the loop does not have to cover the full range of the integer type, rewrite the loop so that the end value is not equal to the maximum value of the integer type. For example, replace:

N=intmax('int16')
for k=N-10:N
with:
for k=1:10

  • The loop index decrements by 1.

  • The end value equals the minimum value of the integer type.

If the loop does not have to cover the full range of the integer type, rewrite the loop so that the end value is not equal to the minimum value of the integer type. For example, replace:

N=intmin('int32')
for k=N+10:-1:N
with:
for k=10:-1:1

  • The loop index increments or decrements by 1.

  • The start value equals the minimum or maximum value of the integer type.

  • The end value equals the maximum or minimum value of the integer type.

If the loop must cover the full range of the integer type, cast the type of the loop start, step, and end values to a bigger integer or to double. For example, rewrite:

M= intmin('int16');
N= intmax('int16');
for k=M:N
	% Loop body
end
as:
M= intmin('int16');
N= intmax('int16');
for k=int32(M):int32(N)
	% Loop body
end

  • The loop index increments or decrements by a value not equal to 1.

  • On the last loop iteration, the loop index is not equal to the end value.

Rewrite the loop so that the loop index in the last loop iteration is equal to the end value.

Character Size

MATLAB supports 16-bit characters, but the generated code represents characters in 8 bits, the standard size for most embedded languages like C. See Encoding of Characters in Code Generation.

Order of Evaluation in Expressions

Generated code does not enforce order of evaluation in expressions. For most expressions, order of evaluation is not significant. However, for expressions with side effects, the generated code may produce the side effects in different order from the original MATLAB code. Expressions that produce side effects include those that:

  • Modify persistent or global variables

  • Display data to the screen

  • Write data to files

  • Modify the properties of handle class objects

In addition, the generated code does not enforce order of evaluation of logical operators that do not short circuit.

For more predictable results, it is good coding practice to split expressions that depend on the order of evaluation into multiple statements.

  • Rewrite

    A = f1() + f2();

    as

    A = f1();
    A = A + f2();

    so that the generated code calls f1 before f2.

  • Assign the outputs of a multi-output function call to variables that do not depend on one another. For example, rewrite

    [y, y.f, y.g] = foo;

    as

    [y, a, b] = foo;
    y.f = a;
    y.g = b;
    

  • When you access the contents of multiple cells of a cell array, assign the results to variables that do not depend on one another. For example, rewrite

    [y, y.f, y.g] = z{:};
    

    as

    [y, a, b] = z{:};
    y.f = a;
    y.g = b;
    

Termination Behavior

Generated code does not match the termination behavior of MATLAB source code. For example, if infinite loops do not have side effects, optimizations remove them from generated code. As a result, the generated code can possibly terminate even though the corresponding MATLAB code does not.

Size of Variable-Size N-D Arrays

For variable-size N-D arrays, the size function might return a different result in generated code than in MATLAB source code. The size function sometimes returns trailing ones (singleton dimensions) in generated code, but always drops trailing ones in MATLAB. For example, for an N-D array X with dimensions [4 2 1 1], size(X) might return [4 2 1 1] in generated code, but always returns [4 2] in MATLAB. See Incompatibility with MATLAB in Determining Size of Variable-Size N-D Arrays.

Size of Empty Arrays

The size of an empty array in generated code might be different from its size in MATLAB source code. See Incompatibility with MATLAB in Determining Size of Empty Arrays.

Size of Empty Array That Results from Deleting Elements of an Array

Deleting all elements of an array results in an empty array. The size of this empty array in generated code might differ from its size in MATLAB source code.

CaseExample CodeSize of Empty Array in MATLABSize of Empty Array in Generated Code
Delete all elements of an m-by-n array by using the colon operator (:).
coder.varsize('X',[4,4],[1,1]);
X = zeros(2);
X(:) = [];
0-by-01-by-0
Delete all elements of a row vector by using the colon operator (:).
coder.varsize('X',[1,4],[0,1]);
X = zeros(1,4);
X(:) = [];
0-by-01-by-0
Delete all elements of a column vector by using the colon operator (:).
coder.varsize('X',[4,1],[1,0]);
X = zeros(4,1);
X(:) = [];
0-by-00-by-1
Delete all elements of a column vector by deleting one element at a time.
coder.varsize('X',[4,1],[1,0]);
X = zeros(4,1);
for i = 1:4
    X(1)= [];
end
1-by-00-by-1

Binary Element-Wise Operations with Single and Double Operands

If your MATLAB code contains a binary element-wise operation that involves a single type operand and a double type operand, the generated code might not produce the same result as MATLAB.

For such an operation, MATLAB casts both operands to double type and performs the operation with the double types. MATLAB then casts the result to single type and returns it.

The generated code casts the double type operand to single type. It then performs the operation with the two single types and returns the result.

For example, define a MATLAB function foo that calls the binary element-wise operation plus.

function out = foo(a,b)
out = a + b;
end

Define a variable s1 of single type and a variable v1 of double type. Generate a MEX function for foo that accepts a single type input and a double type input.

s1 = single(1.4e32); 
d1 = -5.305e+32; 
codegen foo -args {s1, d1} 

Call both foo and foo_mex with inputs s1 and d1. Compare the two results.

ml = foo(s1,d1); 
mlc = foo_mex(s1,d1);
ml == mlc
ans =

  logical

   0

The output of the comparison is a logical 0, which indicates that the generated code and MATLAB produces different results for these inputs.

Floating-Point Numerical Results

The generated code might not produce the same floating-point numerical results as MATLAB in these:

 When computer hardware uses extended precision registers

 For certain advanced library functions

 For implementation of BLAS library functions

NaN and Infinity

The generated code might not produce exactly the same pattern of NaN and Inf values as MATLAB code when these values are mathematically meaningless. For example, if MATLAB output contains a NaN, output from the generated code should also contain a NaN, but not necessarily in the same place.

The bit pattern for NaN can differ between MATLAB code output and generated code output because the C99 standard math library that is used to generate code does not specify a unique bit pattern for NaN across all implementations. Avoid comparing bit patterns across different implementations, for example, between MATLAB output and SIL or PIL output.

Negative Zero

In a floating-point type, the value 0 has either a positive sign or a negative sign. Arithmetically, 0 is equal to -0, but some operations are sensitive to the sign of a 0 input. Examples include rdivide, atan2, atan2d, and angle. Division by 0 produces Inf, but division by -0 produces -Inf. Similarly, atan2d(0,-1) produces 180, but atan2d (-0,-1) produces -180.

If the code generator detects that a floating-point variable takes only integer values of a suitable range, then the code generator can use an integer type for the variable in the generated code. If the code generator uses an integer type for the variable, then the variable stores -0 as +0 because an integer type does not store a sign for the value 0. If the generated code casts the variable back to a floating-point type, the sign of 0 is positive. Division by 0 produces Inf, not -Inf. Similarly, atan2d(0,-1) produces 180, not -180.

Code Generation Target

The coder.target function returns different values in MATLAB than in the generated code. The intent is to help you determine whether your function is executing in MATLAB or has been compiled for a simulation or code generation target. See coder.target.

MATLAB Class Property Initialization

Before code generation, at class loading time, MATLAB computes class default values. The code generator uses the values that MATLAB computes. It does not recompute default values. If the property definition uses a function call to compute the initial value, the code generator does not execute this function. If the function has side effects such as modifying a global variable or a persistent variable, then it is possible that the generated code can produce different results that MATLAB produces. For more information, see Defining Class Properties for Code Generation.

MATLAB Class Property Access Methods That Modify Property Values

When using objects with property access methods, simulation results can differ from MATLAB results. These differences occur when the objects are:

  • Input to or output from an entry-point function.

  • Passed to or returned from an extrinsic function.

  • Loaded into memory by using load.

The results can differ under these conditions:

  • A get method returns a different value from the stored property value.

  • A set method modifies an input value before assigning it to the property.

  • A get method or a set method has side effects such as modifying a global variable or writing to a file.

Results can differ due to inconsistencies in the use of property access methods when MATLAB and the simulation software pass objects to each other:

  • If you return an object from an extrinsic function, MATLAB passes the object to the simulation software. The simulation software creates its own version of the object. To provide property values to the object creation process, MATLAB calls get methods. The object creation process assigns these property values from MATLAB directly to the new object without calling set methods.

  • When you pass an object to an extrinsic function for execution in MATLAB, the simulation software passes the object to MATLAB. MATLAB creates its own version of the object. To provide property values to MATLAB, instead of using get methods, the simulation software directly reads the property values. To assign property values in the MATLAB version of the object, the creation process uses set methods.

To avoid differences in results between MATLAB and simulation, do not use classes with property access methods in these cases.

For more information, see Defining Class Properties for Code Generation.

MATLAB Classes in Nested Property Assignments That Have Set Methods

When you assign a value to a handle object property, which is itself a property of another object, and so on, then the generated code can call set methods for handle classes that MATLAB does not call.

For example, suppose that you define a set of variables such that x is a handle object, pa is an object, pb is a handle object, and pc is a property of pb. Then you make a nested property assignment, such as:

x.pa.pb.pc = 0;

In this case, the generated code calls the set method for the object pb and the set method for x. MATLAB calls only the set method for pb.

MATLAB Handle Class Destructors

The behavior of handle class destructors in the generated code can be different from the behavior in MATLAB in these situations:

  • The order of destruction of several independent objects might be different in MATLAB than in the generated code.

  • The lifetime of objects in the generated code can be different from their lifetime in MATLAB.

  • The generated code does not destroy partially constructed objects. If a handle object is not fully constructed at run time, the generated code produces an error message but does not call the delete method for that object. For a System object™, if there is a run-time error in setupImpl, the generated code does not call releaseImpl for that object.

    MATLAB does call the delete method to destroy a partially constructed object.

For more information, see Code Generation for Handle Class Destructors.

Variable-Size Data

See Incompatibilities with MATLAB in Variable-Size Support for Code Generation.

Complex Numbers

See Code Generation for Complex Data.

Converting Strings with Consecutive Unary Operators to double

Converting a string that contains multiple, consecutive unary operators to double can produce different results between MATLAB and the generated code. Consider this function:

function out = foo(op)
out = double(op + 1);
end

For an input value "--", the function converts the string "--1" to double. In MATLAB, the answer is NaN. In the generated code, the answer is 1.