More efficient way for doing for and while loops.

21 vues (au cours des 30 derniers jours)
Kranthidhar
Kranthidhar le 1 Mar 2014
Commenté : Bee le 9 Jan 2019
Hi, I understand that in matlab for loops and while loops are some-what inefficient; I was wondering if there was an alternate, more efficient way of doing loops. This would apply to just basic for loop and while loop problems. Let me know if there is a simple way, but if there is an advanced method please also mention it.
-Thanks

Réponses (2)

Image Analyst
Image Analyst le 1 Mar 2014
for loops are not always bad. In fact there were cases with older versions of MATLAB where a for loop was faster than linear indexing (vectorizing). With the newer versions of MATLAB the for loops are a lot faster and can do millions of iterations in just a fraction of a second, so it's not always the for loop itself but how you are accessing the memory . For example with large arrays, for max speed, have the row loop be the inner loop and the column loop be the outer loop because it goes down memory in rows first, before it moves over to the next column.
  1 commentaire
Bee
Bee le 9 Jan 2019
That is a very important information, which I'll use wight now: row loops should be the inner loop. Thanks mate!!!

Connectez-vous pour commenter.


John D'Errico
John D'Errico le 1 Mar 2014
Modifié(e) : John D'Errico le 1 Mar 2014
No, there is NOT an efficient way to do a for or while loops, at least not more efficient than for and while.
There are inefficient things you can do, however, that would take a book to cover every foolish thing you might try and tell you not to do those things. (As a hint, failing to preallocate arrays and vectors that you will grow dynamically is perhaps the worst thing I see done often.)
Learn to use the profile tool in MATLAB, and read MATLAB Answers. You will learn what to do and what not to do.

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