For loop faster in main script than from within function

1 vue (au cours des 30 derniers jours)
Davide Alonzo
Davide Alonzo le 18 Mar 2020
Réponse apportée : Yash le 20 Juil 2025
Hi all,
I wrote a for loop to simulate a model in a matlab script. Since the loop is lengthy I lated decided to write a separate function for it and call it from the "main" script.
Somewhat surprisingly I found out that the for loop now runs much slowlier than before and I cannot figure out why. Surely, calling a function increases the memory used by the program, but this is still well below the physical memory available (in total matlab use about 2.5GB and my system has 16GB of RAM).
Can anyone explain me what could be the reason?

Réponses (1)

Yash
Yash le 20 Juil 2025
The function overhead in and of itself increases the memory usage. However, if you pass large arrays or structures as input/output arguments, MATLAB may need to copy data (especially if you modify it inside the function). This can make execution slower if you are working with large arrays.
To try to reduce the memory footprint, try these steps:
  • If you are passing large arrays to the function and modifying them, try to minimize unnecessary modifications or use persistent variables if appropriate.
  • Use MATLAB Profiler to identify the bottleneck in the script.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by