How to exit an if else loop without continuing with the other lines of code?

7 views (last 30 days)
This is my code
prompt = 'Which Schedule Should Be Used? (1/2) \n';
x = input(prompt);
if x == 1
connection = connection_schedule1();
elseif x == 2
connection = connection_schedule2();
else
fprintf('Unrecognized Input \n')
end
connection_schedule1 and connection_schedule2 are two functions that make a schedule for my code. If someone enters any other term than 1 or 2, I would like to display the message 'Unrecognized Input' and exit without proceeding through the next lines of code. Is this possible? Currently, my error message is displayed but it shows also other error in the succeeding lines of code that requires the schedules that I input. It would also be helpful if I can bring back the execution to the first line shown here if an invalid input is provided. Many thanks in advance.
  1 Comment
Stephen23
Stephen23 on 27 May 2020
"It would also be helpful if I can bring back the execution to the first line shown here if an invalid input is provided"
Use a while or a for loop.

Sign in to comment.

Answers (1)

Arjun
Arjun on 6 Dec 2024
I see that you want execute different functions based on the user input and if the input is unrecognized then you want them to re-enter their choice.
The current workflow uses an "if-elseif-else" construct, which inherently does not require an explicit exit because only one of the conditions is executed based on its order. If the "if" condition is true, the statements within it are executed, and all subsequent "elseif" and "else" blocks are skipped. If the "if" condition is false, the control checks the "elseif" conditions in sequence. The first true "elseif" condition executes its block, skipping the rest. If none of the "if" or "elseif" conditions are true, the "else" block is executed.
However, this construct does not allow returning to a previous point, which is why a "while" loop is necessary to repeatedly prompt the user until a valid choice is made. In such cases, an infinite "while" loop is used with a "break" statement to exit the loop once a valid input is received.
Kindly refer to the code below for better understanding:
while true
prompt = 'Which Schedule Should Be Used? (1/2) \n';
x = input(prompt);
if x == 1
connection = connection_schedule1();
break; % Exit the loop on valid input
elseif x == 2
connection = connection_schedule2();
break; % Exit the loop on valid input
else
fprintf('Unrecognized Input \n');
% Optionally, you can add a pause or clear command here
% pause(1); % Pause for 1 second before re-prompting
end
end
Kindly refer to the documentation of "while" and "break" for using them efficiently:
I hope this helps!

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!