More efficient way for doing for and while loops.

42 views (last 30 days)
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

Answers (2)

Image Analyst
Image Analyst on 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 Comment
Bee
Bee on 9 Jan 2019
That is a very important information, which I'll use wight now: row loops should be the inner loop. Thanks mate!!!

Sign in to comment.


John D'Errico
John D'Errico on 1 Mar 2014
Edited: John D'Errico on 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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!