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

StackOverflow https://stackoverflow.com/questions/17305159

  •  01-06-2022
  •  | 
  •  

문제

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!

도움이 되었습니까?

해결책

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

다른 팁

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.

If you know where to skip you could do something like

ind = [1:2,8:10]
r(ind) = ind
r(3) = 20

This way you also avoid for loop. If you can't determine how many loops you do before skipping use two different loops and use break keyword to stop the first iteration.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top