Is there any other way of using a loop without the loop command like for, while etc..

2 vues (au cours des 30 derniers jours)
Hi there, just as the title say, is there any other way? I'm currently runing a programe with take quite a while to execute because of the loop...so just curiuos if anyone know how to do a loop without using the loop command?
Ta, Rak

Réponse acceptée

Walter Roberson
Walter Roberson le 30 Nov 2011
You can hide the loop by using arrayfun() or cellfun() or the like, but those are convenience functions that will loop internally.
"for" and "while" are the only two basic repetition structures in MATLAB.
You could construct a recursive function to do the looping implicitly, but that is unlikely to be any faster.
The most common cause of slow loops is a failure to preallocate space for the outputs, which (until 2011b anyhow) results in the new memory having to be continually allocated, old memory copied to new, old memory deallocated. That can be very bad for performance.
"for" loops have not been especially slow for several years, and in modern versions can be faster than vectorizing. It is what is in the body of the for loop that can be slow.
You should consider using the profiler to find out where you program is slow.
  1 commentaire
Jan
Jan le 21 Juil 2013
@francesco: Especially for the FOR loops, which profit form the JIT acceleration, the profiler shows misleading results: The JIT can reorder the sequence of the commands to reduce the run-time. But this would confuse the profiler and therefore the JIT acceleration is automatically disabled when the profiler is started. What a pity, that this reduces the use of the profiler considerably!
Some TIC/TOCs can be more useful then.

Connectez-vous pour commenter.

Plus de réponses (1)

francesco
francesco le 21 Juil 2013
very useful explanation Walter :)

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