or-function with switch

조회 수: 22 (최근 30일)
Tor Fredrik Hove
Tor Fredrik Hove 2011년 10월 15일
Can you not use or in one of the cases for switch. I tried here but it did not call it at all:
I know about the case {2, 3} possibility just wondered about if or is a possibility here
here is my function:
function grade=switchletgrade1(quiz)
if quiz<0 ||quiz>4
grade='X'
else
switch quiz
case 3 || 2
grade='B'
case 4
grade='A'
otherwise
grade='C'
end
end
end

채택된 답변

Walter Roberson
Walter Roberson 2011년 10월 15일
No, 3||2 cannot be used in that context. Each case list is executed (unless the switch matched earlier), so 3||2 as a case label is evaluated as logical(3)||logical(2) which is true||true which is true which has the numeric value 1. Coding 3||2 as a case is thus equivalent to coding a 1 at that point.
The {} notation is the one you need for multiple possibilities.
  댓글 수: 2
Tor Fredrik Hove
Tor Fredrik Hove 2011년 10월 15일
here i have tried with || it seems like case just ignores it. Does what you say by saying true mean that it uses it like other functions does excecute from true after an if? If so what is the case with this excecution that I did here:
http://bildr.no/view/1001313
Jan
Jan 2011년 10월 15일
Please, Tor, post the code instead of screenshots.
"case 2||3" is equivalent to "case true", because "2||3" is equivalent to "logical(2)||logical(3)".
You want: "case {2, 3}". Reading the documentation is stringly recommended: "doc switch" and the Getting Started chapters.

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

추가 답변 (1개)

William
William 2011년 10월 15일
It works. You had one too many "end" statements. You might want to make it a little bit more stable by using more "=<" statements in the switch statement otherwise a 3.4 is going to be a "C"
function grade=switchletgrade1(quiz)
if quiz<0 ||quiz>4
grade='X'
else
switch quiz
case 3 || 2
grade='B'
case 4
grade='A'
otherwise
grade='C'
end
end
  댓글 수: 1
Walter Roberson
Walter Roberson 2011년 10월 15일
Tor does *not* have too many 'end' statements. Refer to the documentation for "function", which says,
You can terminate any type of function with an end statement, but doing so is not required unless the file containing the function also contains one or more nested functions. Within this file, every function (including primary, nested, private, and subfunctions) must be terminated with an end.

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by