How to make a for loop jump multiple iterations, if a condition happens?

12 views (last 30 days)
I have to create a code that reads columns of an excel document, then it has to choose between three options. I called them option -1, option 0 and option 1. If -1 or 1 are choosen, then the code needs to jump six rows of the excel document. For example, if while reading row 4, it chooses 1, then the next row it should read should be 10. I tried to do something like this:
for r = 1:row %Reads the row of the excel file
if genes(r) == -1
%Does something
r = r+6 %r is now r+6
elseif genes(p,r) == 0
%Does Something
elseif genes(p,r) == 1
r = r+6 %r is now r+6
end
end
But in the next iteration the r is always the next number, and not r+6.
Can someone help.

Accepted Answer

Star Strider
Star Strider on 26 Jan 2018
‘But in the next iteration the r is always the next number, and not r+6.’
You cannot change the index variable within a for loop. It will increment according to the instructions given to it in the for statement.
Consider using a while loop. Since you know the row size of the matrix you are working with, one option for the condition in the while statement would be to continue iterating so long as the calculated value of ‘r’ for the next iteration is less than or equal to the row size of the matrix. (If ‘r’ is always an integer, this test should not be a problem.) You can use ‘r’ as the only variable, or if you need to write consecutive rows to another output matrix, add a second row index for it that increments by 1, so you do not have gaps of zero rows in the output matrix.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!