# Code with Switch case and if

37 views (last 30 days)
Andrea Miceli on 31 Mar 2021
Commented: Andrea Miceli on 1 Apr 2021
Hello to evreybody, i am not able to figure out why this code is not working. When I run the code it always give me back that the grade is '5' even if the points are >9.
For example, I tried to change the 'case' condition and if use {40,41,42,43,44,45,46,47,48,49,50} it gives me back the right grade if I use '(points >= 40 && points <= 50)' it doesn't work as I want. Can somebody tell me how to fix the condition for the switch case?
%code
points=randi([-5,55]);
if (points<0) || (points>50)
return
end
switch points
case (points >= 40 && points <= 50)
case (points>=30 && points<=39)
case (points>=20 && points<=29)
case (points>=10 && points<=19)
otherwise (points>=0 && points<=9)
end

Cris LaPierre on 31 Mar 2021
Edited: Cris LaPierre on 31 Mar 2021
A switch statement looks for the case that is true. The conditional for each of your cases returns a true/false value. This means you switch on true, not points.
switch true
case (points >= 40 && points <= 50)
case (points>=30 && points<=39)
case (points>=20 && points<=29)
case (points>=10 && points<=19)
otherwise (points>=0 && points<=9)
end
##### 2 CommentsShowHide 1 older comment
Andrea Miceli on 31 Mar 2021
thank you!

Steven Lord on 31 Mar 2021
Unless this is part of a homework assignment where you're required to use switch / case, I'd use a different tool. I'd use logical indexing or discretize which have an added benefit of being vectorized.
points=randi([-5,55], 10, 1);
% logical indexing
case1 = (points >= 40) & (points <= 50);
case2 = (points >= 30) & (points <= 39);
case3 = (points >= 20) & (points <= 29);
case4 = (points >= 10) & (points <= 19);
case5 = (points >= 0) & (points <= 9);
% discretize
boundaries = [-Inf, 0, 10, 20, 30, 40, 50];
% anything in the range [boundaries(1), boundaries(2)) gets grades(1)
% anything in the range [boundaries(2), boundaries(3)) gets grades(2)
% etc
grades = ["NA", "5", "4", "3", "2", "1"];
'VariableNames', ["Raw points", "Logical indexing", "Discretize"])
results = 10×3 table
Raw points Logical indexing Discretize __________ ________________ __________ 11 "4" "4" 29 "3" "3" 15 "4" "4" 5 "5" "5" 23 "3" "3" 36 "2" "2" 14 "4" "4" 51 "NA" <missing> -2 "NA" "NA" 37 "2" "2"
Handling of the right boundary of the last bin in the discretize case requires a little bit of special treatment as does handling of values that are greater than the limit of a grade of 1. I'll leave that as an exercise to you, based on the documentation of the discretize function.
Andrea Miceli on 1 Apr 2021
I was required to use switch/case. Btw your logical operation is very useful. I will practice this for sure! Thank you for your time.