Infinite Loop Of Switch

조회 수: 20 (최근 30일)
Tyann Hardyn
Tyann Hardyn 2021년 8월 30일
답변: Cris LaPierre 2021년 8월 30일
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
%instead of 1 only.
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
Cris LaPierre 2021년 8월 30일
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

추가 답변 (1개)

Image Analyst
Image Analyst 2021년 8월 30일
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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by