What are the efficient ways to generate “mod by constant” code with Embedded Coder (e.g., mod(u, 360))?

9 visualizaciones (últimos 30 días)
I’m looking for an efficient way to compute mod by a compile-time constant in Simulink models that generate C/C++ with Embedded Coder. For example, mod(u, 360) for floating-point or fixed-point signals.
  • Using the two-input Mod block (u mod m) with a literal constant for m (e.g., 360) often generates a helper function call (e.g., rt_modf_snf) rather than an inlined expression, which impacts performance and readability.
  • I’d like inlined code when the modulus is a known constant, and the efficient implementation for fixed-point/integer data types (e.g., turns into multiplies/shifts).
Thanks!

Respuestas (1)

MathWorks Fixed Point Team
MathWorks Fixed Point Team el 2 de Sept. de 2025
If your goal is to generate efficient, inlined code for mod by a known constant, use the Modulo by Constant block rather than the two-input Mod block.
Why:
  • Two-input Mod block: The second input is treated as a signal, not as a literal constant during code generation. For floating-point, this commonly results in a call to a runtime helper (e.g., rt_modf_snf(u, 360.0F)) to preserve numerical behavior across edge cases.
  • Modulo by Constant block: The modulus is a parameter (compile-time constant). Embedded Coder can inline the operation and select specialized implementations. Docs links: https://www.mathworks.com/help/fixedpoint/ref/modulobyconstant.html
Examples:
Floating-point code generation (using R2024b):
Fixed-point code generation (using R2024b):

Categorías

Más información sobre Fixed Point en Help Center y File Exchange.

Productos


Versión

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by