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

2 views (last 30 days)
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 Comments
John D'Errico
John D'Errico on 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 on 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

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 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 Comments
John D'Errico
John D'Errico on 30 Oct 2018
Edited: John D'Errico on 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.

Sign in to comment.

More Answers (0)

Categories

Find more on Argument Definitions in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!