# Infinite Loop Of Switch

21 views (last 30 days)
Tyann Hardyn on 30 Aug 2021
Answered: Cris LaPierre on 30 Aug 2021
Hi, Matlab Community
Iam just curious about this. Could matlab do an infinite loop by using switch and case, to be exact when the input parameter is not same as the desire input?
Iam typing an example code like this :
%Case 1
a1 = [2, 1; 1, 3];
inverse_a1 = inv(a1);
%Case 2
a2 = [2, -4; -3, 6];
inverse_a2 = inv(a2);
%Case 3
a3 = [2.01, 1.5; 4, 3];
inverse_a3 = inv(a3);
in = input('Enter the number of case (1, 2, or 3) = ');
switch input('Type the case number (1, 2, or 3) = ')
case 1
out1 = sprintf("Matrix inversion from case 1 is");
disp(out1);
disp(inverse_a1)
case 2
out2 = sprintf("Matrix inversion from case 2 is");
disp(out2);
disp(inverse_a2)
case 3
out3 = sprintf("Matrix inversion from case 3 is");
disp(out3);
disp(inverse_a3)
otherwise
disp(in); %I want to create this otherwise statement to be Infinite Loop of asking to the user
end
By using the above code, if the input is not 1, 2, or 3, it will deliver us directly to the otherwise statement that occurs only 1 times and then make us out from Switch region (end the switch). Could it possible to create an infinite loop so then we will continuously meet the variable of " in " ( input('Enter the number of case (1, 2, or 3) = '); ) again and again?
Thank you very much..... /.\ /.\ /.\

Cris LaPierre on 30 Aug 2021
Switch statements do not loop, so no, it is not possible to create an infinite loop using one.
If you want to create a loop, consider incorporating a while loop into your code.
in = 0;
% While loop repeats until in is 1,2 or 3
while ~ismember(in,1:3)
in = input('Enter the number of case (1, 2, or 3) = ');
end
% Only reaches switch statement if in is 1, 2 or 3
switch in
case 1
out1 = sprintf("Matrix inversion from case 1 is");
disp(out1);
disp(inverse_a1)
case 2
out2 = sprintf("Matrix inversion from case 2 is");
disp(out2);
disp(inverse_a2)
case 3
out3 = sprintf("Matrix inversion from case 3 is");
disp(out3);
disp(inverse_a3)
end

Image Analyst on 30 Aug 2021
No, you'll never have an infinite loop with a switch statement because there is no looping at all. It just goes straight through. If you want one, you'll have to put it inside a while statement:
while true
in = input('Enter the number of case (1, 2, or 3) = ');
switch in
case 1 % etc.
otherwise
end
end % of while. Use control-c to break out