if, or or or or or

73 views (last 30 days)
furcifer
furcifer on 12 Dec 2018
Commented: Walter Roberson on 13 Dec 2018
I'm just wondering if Matlab can string together "or" statements? The current code for a simple menu is using
userinput = input("Select 1,2,3,4 and press enter: ")
if X == 1
disp(stuff)
if X == 2
disp(stuff)
% etc. this is just an example
end
Seems like you should be able to use if X=(1||2||3||4) to avoid the multiple lines of code. Then:
if X = (1||2||3||4)
Y= sprintf ("You selected: ", userinput)
disp(Y)
else
disp("That was not a choice")
end
We're on to using C++ now so I'm thinking along the lines of
cout <<"You seleceted"<< variable<< endl;
This is probably better done as a switch case but I was thinking about booleans when I started to try this.

Accepted Answer

Cris LaPierre
Cris LaPierre on 12 Dec 2018
Edited: Cris LaPierre on 12 Dec 2018
It can, but you have to be a little more specific about it
if X == 1 || X == 2 || X == 3 || X == 4
  9 Comments
Walter Roberson
Walter Roberson on 13 Dec 2018
X = sprintf("You Selected %d",answer);
furcifer
furcifer on 13 Dec 2018
Thanks. I think I got it now. I forgot to save the code and was getting a weird error.
Thanks for all the help.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 12 Dec 2018
Of course MATLAB will let you use input() multiple times.
You might want to consider menu():
buttonNumber = menu('Make a selection', '1', '2', '3', '4');
if buttonNumber == 1
% Code to execute if they clicked 1.
elseif buttonNumber == 2
% Code to execute if they clicked 2.
elseif buttonNumber == 3
% Code to execute if they clicked 3.
elseif buttonNumber == 4
% Code to execute if they clicked 4.
end
  4 Comments
furcifer
furcifer on 13 Dec 2018
I'm studying Matlab and C++ at the same time for an exam. The questions are going to specifically state to use "while", "do while", "if" etc. Looking at this type of question it's possible it could be asked to use boolean operators.
X <= 4
isn't quite as "idiot proof". -4 isn't a choice but the program returns a value. This isn't so much about saving code as trying to make sure how I think gets translated into what's being asked so if my code isn't excatly the same it functions the same way.
Walter Roberson
Walter Roberson on 13 Dec 2018
x >= 1 && x <= 4

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!