Code with Switch case and if
Afficher commentaires plus anciens
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?
Thank you in advance for your help!
%code
points=randi([-5,55]);
if (points<0) || (points>50)
grade = 'NA';
return
end
switch points
case (points >= 40 && points <= 50)
grade='1';
case (points>=30 && points<=39)
grade='2';
case (points>=20 && points<=29)
grade='3';
case (points>=10 && points<=19)
grade='4';
otherwise (points>=0 && points<=9)
grade='5';
end
Réponse acceptée
Plus de réponses (1)
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);
grade1 = repmat("NA", size(points));
% logical indexing
case1 = (points >= 40) & (points <= 50);
grade1(case1) = "1";
case2 = (points >= 30) & (points <= 39);
grade1(case2) = "2";
case3 = (points >= 20) & (points <= 29);
grade1(case3) = "3";
case4 = (points >= 10) & (points <= 19);
grade1(case4) = "4";
case5 = (points >= 0) & (points <= 9);
grade1(case5) = "5";
% 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"];
grade2 = discretize(points, boundaries, grades);
results = table(points, grade1, grade2, ...
'VariableNames', ["Raw points", "Logical indexing", "Discretize"])
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.
1 commentaire
Andrea Miceli
le 1 Avr 2021
Catégories
En savoir plus sur Inertias and Loads dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!