Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MATLAB, how can I skip a pre-determined number of for loop iterations if certain criteria is met?

In Matlab, I am performing calculations during a for loop but am trying to find a way to skip iterations during the for loop if certain criteria are met. I have written out a quick example to illustrate my question.

In the code below, the for loop will go through iterations 1 and 2 and output as expected into r. r(1) will be 1, and r(2) will be 2. Once the for loop runs through iteration 3, the value of 20 will be placed into r(3). After this takes place, then I want the for loop to skip the next 5 iterations and go straight to iteration 8 of the for loop.

for i=1:1:10
    if i==3
        r(i)=20;
        i = i+5;
    else
        r(i) = i;
    end
end

The actual result for r is as follows:

r =

 1     2    20     4     5     6     7     8     9    10

However, I would like for the result to appear similar to the following. (PLEASE NOTE that I am not looking to fill the desired r(4):r(7) with 0 but rather looking to skip for loop iterations 4 through 7 entirely.)

r =

 1     2    20     0     0     0     0     8     9    10

If anyone has advice, that will be greatly appreciated. Thank you!

like image 456
enter_display_name_here Avatar asked Jun 25 '13 18:06

enter_display_name_here


2 Answers

Use a while loop instead of a for loop to increment it manually:

i=1;  // index for loop
k=1;  // index for r
r = zeros(1,10) // pre-allocate/cut is faster
while i <= 10
  if i == 3
    r(i)=20;
    i = i+5;  // skip multiple iterations
  else
    r(k)=i; 
    i=i+1;    // loop increment
    k=k+1;    // vector increment
  end
end
r(k+1:end) = []; // Remove unused portion of the array
like image 78
Kendra Lynne Avatar answered Nov 04 '22 04:11

Kendra Lynne


The most basic implementation is to just omit those from the loop.

for i=  [1:3 8:10]
   if i==3
       r(i)=20;
   else
       r(i) = i;
   end
end

However, that may not meet your needs, if you really need to do dynamic determination of loop indexes. In that case, use a while loop, like this:

i = 1;
while i <= 10
   if i==3
       r(i)=20;
       i = i+5;
   else
       r(i) = i;
       i = i+1
   end

end

As you have seen, there are problems when you try and change the indexing variable wihtin a for loop.

like image 21
Pursuit Avatar answered Nov 04 '22 05:11

Pursuit