Return back to a specific line
    31 次查看(过去 30 天)
  
       显示 更早的评论
    
I have more while and for loop, I need to go beginning. ex:
1.    while ()
 2.           for ()
3.                if (condition) 
4.                      Go back to starting of the code i.e line 1
5.                 else
6.                       code for some action
7.                 end
8.           end
8.           for ()
9.                some calculation
8.           end
9.   end
I need like this, Please help. If I use break, it will break that first for loop only and it will go to next for loop, but I don't want that.
回答(1 个)
  Adam Danz
    
      
 2019-4-18
        
      编辑:Adam Danz
    
      
 2019-4-23
  
      Here's a functional example that you can run or step through in debug mode. The flag 'continueForLoop' determines whether the for-loops will continue execution.
c = 0;                      %counter for while-loop
while c < 5
    % Reset flag (when true, for-loop continues)
    continueForLoop = true;
    for i = 1:5
        if rand(1) < 0.5 && continueForLoop
            % set flag that will ignore the rest of the for-loop
            continueForLoop = false;
        elseif continueForLoop
            disp('For-loop continues')
        end
    end
    if continueForLoop
        for j = 1:3
            x = rand(1);
        end 
    end
    % increment counter
    c = c+1;
end 
2 个评论
  Guillaume
      
      
 2019-4-23
				I would add a break in the first if instead of the ContinueForLoop test. There's no point continuing iterating the first for to just do nothing.
c = 0;                      %counter for while-loop
while c < 5
    % Reset flag (when true, for-loop continues)
    continueForLoop = true;
    for i = 1:5
        if rand(1) < 0.5
            % set flag that will ignore the rest of the for-loop
            continueForLoop = false;
            break;  %and bail out of current for loop
        elseif continueForLoop
            disp('For-loop continues')
        end
    end
    if continueForLoop
        for j = 1:3
            x = rand(1);
        end 
    end
    % increment counter
    c = c+1;
end 
另请参阅
类别
				在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


