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

4 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Walter Roberson
Walter Roberson el 30 de Nov. de 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 comentario
Jan
Jan el 21 de Jul. de 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.

Iniciar sesión para comentar.

Más respuestas (1)

francesco
francesco el 21 de Jul. de 2013
very useful explanation Walter :)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by