For loop faster in main script than from within function

조회 수: 3 (최근 30일)
Davide Alonzo
Davide Alonzo 2020년 3월 18일
답변: Yash 2025년 7월 20일
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?

답변 (1개)

Yash
Yash 2025년 7월 20일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by