break a loop with if in matlab

To break a loop in MATLAB we simply use the break statement. In combination with an if statement, we can break out of a loop as soon as a certain condition is met.

Here's an example of how to do this:

main.m
% loop from 1 to 10
for i = 1:10
    
    % print the value of i
    fprintf('The value of i is: %d\n', i)
    
    % check if i is equal to 5
    if i == 5
        
        % break out of the loop
        break
        
    end
    
end
238 chars
16 lines

In this example, the loop will run from 1 to 10, but as soon as i is equal to 5, the if statement will be true and the break statement will be executed, breaking out of the loop.

Output:

main.m
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 5
105 chars
6 lines

gistlibby LogSnag