Ask Your Question
3

What is the way to break a loop in Matlab when a number is repeated?

asked 2022-07-16 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-07-02 03:00:00 +0000

djk gravatar image

To break a loop in Matlab when a number is repeated, you can use the 'break' statement. Here is an example code:

a = [1 2 3 4 5 6 7 7 8 9];
for i=1:length(a)-1
    if a(i)==a(i+1)
        disp('Number repeated!');
        break;
    end
    disp(['a(', num2str(i), ') = ', num2str(a(i))]);
end

In this code, the 'for' loop goes through all elements of the array 'a'. When two consecutive elements are equal, the 'if' statement is true and the 'break' statement is executed, ending the loop. Otherwise, the loop continues and the message is displayed with the value of each element of 'a'.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-16 11:00:00 +0000

Seen: 18 times

Last updated: Jul 02 '22