if and switch statement

1 vue (au cours des 30 derniers jours)
Micheal McDonagh
Micheal McDonagh le 24 Juin 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

Réponse acceptée

Adam Danz
Adam Danz le 24 Juin 2021
To answer your question, you would use
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

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by