if, or or or or or
Show older comments
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
More Answers (1)
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
on 12 Dec 2018
Image Analyst
on 13 Dec 2018
You can use a switch statement but a switch statement will have one more line of code than an if/else.
Not sure how this full factorial combination generation followed by putting into a string method you're thinking of would work. I can't imagine it being simpler than a simple if/else.
How many are you going to have anyway? Hundreds? My programs typically have well over a thousand lines of code, so what's the big deal on having 3 or 4 extra lines if it's clearer and more intuitive, meaning easier to maintain? Do you really want some tricky, cryptic code just to save a line or two? I'd think not.
Not sure why you accepted that answer
if X == 1 || X == 2 || X == 3 || X == 4
when you can much more simply do
if X <= 4
assuming your user did what you told them to. Anyway, you're still going to have to check for the numbers individually if you want to execute different code depending on the number. So I don't understand why the accepted Answer is ideal. But whatever - it's your program and you can make it as simple or cryptic as you want.
furcifer
on 13 Dec 2018
Walter Roberson
on 13 Dec 2018
x >= 1 && x <= 4
Categories
Find more on Common Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!