Incremental conditions for if statement

조회 수: 16 (최근 30일)
Louis Grainger
Louis Grainger 2021년 4월 22일
답변: Steven Lord 2021년 4월 22일
I'm trying to return an invalid message for any value not inside the parameters.
Given this for loop with an embedded while and if just to check the inputs value.
for i = 1:2
fprintf("iteration %d\n", i);
flag = 1;
while flag == 1
row = input(":");
if row ~= 1
fprintf("invalid input\n");
fprintf("while restarts\n");
flag = 1;
else
fprintf("valid input\n");
flag = 0;
end
end
fprintf("while ends\n");
end
fprintf("end\n");
Is there a way to implement a if row ~= 1:10 condition?
Alternativley is there a way to use switch cases?
  댓글 수: 1
Louis Grainger
Louis Grainger 2021년 4월 22일
Obviously switch case can be used to display valid for 1:10 but it will break the code if any other input is entered.

댓글을 달려면 로그인하십시오.

채택된 답변

Steven Lord
Steven Lord 2021년 4월 22일
If you want to check if a number is not in a given set, use ismember.
x = 1:10;
if ismember(5, x)
disp("5 is in x")
else
disp("5 is not in x")
end
5 is in x
if ismember(pi, x)
disp("pi is in x")
else
disp("pi is not in x")
end
pi is not in x

추가 답변 (0개)

카테고리

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