Search code examples
matlabfor-looperror-handlingskipconditional-breakpoint

How to skip `for` loop index if an error occurs


In Matlab, if an error occurs, how can I skip that certain for loop index and continue to the next index? Note that I do not know which for loop indices will cause the error to occur.

Error: Too many outputs requested. Most likely cause is missing [] around left hand side that has a comma separated list expansion

Let's assume that an error occurs when k = 5. How can I make the for loop skip index k = 5 and continue to k = 6?

for k = 1:10
    do stuff
    if error occurs
       skip k that causes error
       go to next k
    end
end

Solution

  • You can use try for this purpose!

    for k = 1:10
            %do stuff
            try
             % portion of the code where error can occur
            end
    end