Switch results at certain condition

1 view (last 30 days)
Amril Luqman
Amril Luqman on 16 Jun 2021
Commented: Amril Luqman on 17 Jun 2021
g=9.81; %gravity acceleration
v=input('Enter the value of Velocity');
theta=30*pi/180;
% compute and display results
disp('time of flight(s):')
time_ground=2*v*sin(theta)/g;
disp('distance travelled(m):')
distance_traveled=v*cos(theta)*time_ground;
if distance_traveled >=10
disp('Passed')
else
disp('Failed')
end
if distance_traveled>=10;
grade=A;
switch(grade)
case distance_traveled>10
fprintf('B')
case distance_traveled>15
fprintf('A')
end
I want to make the grade change at certain condition. For example, if the distance traveled is more than 10, then the grade is B. When the distance traveled is more than 15, the grade is A. Please correct what am i doing wrong here. If possible, i dont want to get rid of the switch command. Thanks in advance.

Answers (1)

Steven Lord
Steven Lord on 16 Jun 2021
switch is not the right tool for this job. Use if instead.
switch is intended when you intend to distinguish between a fixed discrete set of possibilities.
pet = 'dog';
switch pet
case 'cat'
disp('meow')
case 'parrot'
disp('squawk')
case 'dog'
disp('bark')
otherwise
error('I don''t know what sound this type of pet makes')
end
bark
if is intended for when you have one or more criteria you want to check.
p = pi;
if p < 1
disp('less than 1')
elseif p < 2
disp('less than 2')
elseif p < 3
disp('less than 3')
else
disp('not less than 3')
end
not less than 3
  1 Comment
Amril Luqman
Amril Luqman on 17 Jun 2021
Thank you, but after doing research by myself, it appear i can use these:
switch true
case (distance_traveled>10 && distance_traveled<=20)
disp('Grade C')
case (distance_traveled>20 && distance_traveled<=30)
disp('Grade B')
case (distance_traveled>=30)
disp('Grade A')
It works just like what i intented.

Sign in to comment.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!