- 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.
For loop faster in main script than from within function
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
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:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!