MATLAB Answers

using greater than or less than in 'switch' and 'case' expressions

916 views (last 30 days)
Harry
Harry on 27 Jun 2013
Answered: Lana Aljilani on 14 Apr 2020
I don't quite understand how to use the switch and case expressions to calculate when a variable is less than or greater than a particular value. Something like this:
x = 7
switch x
case > 5
disp ('x is greater than 5')
case < 5
disp ('x is less than 5')
otherwise
disp ('error')

  0 Comments

Sign in to comment.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 27 Jun 2013
use if...elseif..else..end
if x > 5
disp ('x is greater than 5')
elseif x < 5
disp ('x is less than 5')
else
disp ('error')
end

  0 Comments

Sign in to comment.

More Answers (2)

Tom
Tom on 27 Jun 2013
inequalities are best used with IF statements rather than switch; switch is useful for handling a variety of known values.
If you wanted to write it using a switch statement, it might be like this:
switch n
case num2cell(1:4)
disp('n is less than 5')
case num2cell(6:10)
disp('n is greater than 5')
otherwise
disp('error')
end
But clearly this only works for values of n between 1 and 10.

  0 Comments

Sign in to comment.


Lana Aljilani
Lana Aljilani on 14 Apr 2020
i want grade of student by switch order ( by input the mark )

  0 Comments

Sign in to comment.

Tags


Translated by