Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to exit from two nested for loop in matlab

Tags:

loops

matlab

I have a while loop in which I have two for loops. I have a condition in the innermost for loop. Whenever that condition is satisfied I want to exit from both the two for loops and continue within the while loop:

while (1)
    for x=1:20
        for y=1:30
            if(condition)

            end
        end
    end
end

Does Matlab have something like a labeled statement in Java, or is there another way to do this?

like image 566
Amit Kumar Avatar asked Nov 30 '13 16:11

Amit Kumar


2 Answers

One ever so slightly more elegant way than Luis Mendo's. ;-)

while (1)
    for x=1:20
        for y=1:30
            quit = (condition);
            if quit
                break;
            end
        end
        if quit
            break;
        end
    end
end
like image 187
A. Donda Avatar answered Oct 21 '22 00:10

A. Donda


Only slightly more elegant than A.Donda's answer (avoids testing the condition twice):

while 1
    for x=1:20
        for y=1:30
            quit = 0;
            if (condition)
                quit = 1;
                break;
            end
        end
        if quit
            break;
        end
    end
end
like image 22
Luis Mendo Avatar answered Oct 21 '22 00:10

Luis Mendo