# if and switch statement

2 views (last 30 days)
Micheal McDonagh on 24 Jun 2021
I have 2 sets of code below. One is with an if statement, and the other is with a switch statement.
code 1 is fine, but for code 2, I wanted to practice doing this code with a switch instead of if.
for code 2, I want the range of the input to be anthing from 1 to 50, so then I would have
case {1,2,3,4,5,6,7.8,9,10,11...50}
etc, is there a simply way to write this. As writing 1 to 50 is inefficient.
Hope my question makes sense!
% Code 1 if
clc, clear all, close all
c = 331;
temp = input('Enter temp value: ');
if temp < 0 || temp > 50
disp('Error in temperature value, enter a value in the range of 0 to 50')
else
speed = c+0.6*temp;
fprintf('\nThe speed is %.1f\n\n', speed);
end
% code 2 switch
clc, clear all,close all
c = 331;
temp = input('Temperature in celsius: ');
switch temp
case {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20} % I gave up after 20....
speed = c*331*0.6*temp;
fprintf('Speed is %.2f\n\n',speed)
otherwise
disp('Error in temperature value, enter a value in the range of 0 to 50')
end

Adam Danz on 24 Jun 2021
case num2cell(1:50)
But a switch/case is not the optimal method in this context. What if the user entered 22.5? 22.5 does not match any of the values 1:50.
A conditional statement would be much better not only because it avoids the problem above but it's more efficient than a switch/case.
if temp >= 1 && temp <= 50
Even if you only want positive integers,
if temp >= 1 && temp <= 50 && mod(temp,1)==0