필터 지우기
필터 지우기

clarification of the use 'switch case'

조회 수: 5 (최근 30일)
Scragmore
Scragmore 2011년 12월 4일
Hi,
I would just like a little clarification of the use of 'switch case', most of the examples I have looked at showed examples where only one of the 'case' are true. I have not found an explanation that makes it clear I can return any number of true or positive values.
My example, I have a number and want to ask 5 questions and execute code/function at all true values. All questions may be true, false or any combination in between.
switch 25
case >20
do a
case mod(3)
do b
case ==5^2
do c
end
Does the code execute every 'case' irrelevant of previous answer, if so do I use break or continue to exit the switch.
Regards,
AD

답변 (1개)

Amith Kamath
Amith Kamath 2011년 12월 4일
In MATLAB switch blocks, only the first matching case executes:
result = 52;
switch(result)
case 52
disp('result is 52')
case {52, 78}
disp('result is 52 or 78')
end
This code returns
result is 52
Hope this clarifies your questions!
  댓글 수: 3
Amith Kamath
Amith Kamath 2011년 12월 4일
I wonder why that's not so obvious, considering the number of such questions here!
Scragmore
Scragmore 2011년 12월 4일
Ok,
So it only executes the first true answer before exiting the 'switch case' statement. So to perform a number of queries on a variable and execute each time a true statement is returned I would have to write successive 'if end' statements.
x = 25;
if x > 20
do a;
end
if mod(x,n)
do b;
end
if x == 5^2
do c;
end
...
Sorry this was not 100% clear when I read those docs which was why I requested clarification. Or hoping someone would direct me to an alternative function that may have been more suitable.
Thanks,
AD

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

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by