does anyone know how to rewrite this into switch/case statements

6 vues (au cours des 30 derniers jours)
Pablo Garcia
Pablo Garcia le 30 Oct 2018
Modifié(e) : John D'Errico le 30 Oct 2018
n=input('Please enter a positive or negative integer: ');
if n < -2 || n > 5
disp(n/2)
else
if n <= 3
if n >= 0
disp(floor(n/2))
else
disp(ceil(n))
end
else
disp(1)
end
end
  6 commentaires
John D'Errico
John D'Errico le 30 Oct 2018
Yeah, I figured it was HW. Stupid stuff. Teacher makes you do silly things for no good reason. Grump. Rant. Grumble. ;-)
So, are you asking how to do different things, based on which range n falls in, using a switch/case?
Pablo Garcia
Pablo Garcia le 30 Oct 2018
The homework is basically just asking us to switch the above code from an if/if-else statement to a switch/case statement that still keeps the same purpose. I understand how to use switch/case statements but I'm having trouble with the inequalities

Connectez-vous pour commenter.

Réponse acceptée

John D'Errico
John D'Errico le 30 Oct 2018
The immediate answer is to look at histcounts. It will allow you to set up a series of break points, returning an integer that indicates which regime a number falls into. So it looks like the various cases you might care about are:
breaks = [-2 0 3 5]
Then the third output from histcounts will be an integer, depending on which interval a point falls in. The problem is, you have a special issue, in that histcounts tests to see if a point is in an interval if it is >= the breaks.
So histc would put 3 and 4 into the same bin! And it looks like you wants histcounts to do something different for n==3 versus n==4.
If you know that n is always an integer, that means you wanted to set the break points as
breaks = [-2 0 4 5];
Anyway, histcounts may be beyond the scope of this problem, since it has a simple resolution.
switch n
case {-1 -2}
% do whatever you might do when n==-1 or -2
case {0 1 2 3}
% do whatever you might do when n lives in this range
case {4 5}
% do whatever you might do when n lives in this range
otherwise
% we covered all the other cases, so this is what happens when n < -2 or > 5
disp(n/2)
end
  3 commentaires
Bruno Luong
Bruno Luong le 30 Oct 2018
"otherwise"
John D'Errico
John D'Errico le 30 Oct 2018
Modifié(e) : John D'Errico le 30 Oct 2018
That is exactly what otherwise does. It covers all cases that were not explicitly mentioned in the cases. The problem would be if you wanted to do something different for n<-2 compared to n>5. Then you would need to get trickier. For example, you might need to put an if inside the otherwise block.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by