OR statement in MATLAB issue

2 views (last 30 days)
Viraj Rodrigo
Viraj Rodrigo on 28 Apr 2018
Edited: John D'Errico on 28 Apr 2018
Hey guys so I have this problem with code assigned to 'x' variable. I want to use OR statement (i.e. if strcmp of x is Black OR Brown OR Orange, then display 'Input saved') and move on to variable 'p'. But when I enter anything (even a given colour) or nothing at all and press enter, then the program would loop back to x. How do I fix this?
Please help
Thank you <3 :)
x = [];
while isempty(x)
x = lower(input('Select colour for Disc1: "Black", "Brown", "Orange", 's'));
if strcmp(x, 'Black') || strcmp(x,'Brown') || strcmp(x,'Orange')
disp('Input saved')
else
disp('Error: Please choose a colour')
x = [];
end
end
p = [];
while isempty(p)
p = lower(input('Select colour for Disc2: "Black", "Brown", "Orange", 's'));
end
  1 Comment
Viraj Rodrigo
Viraj Rodrigo on 28 Apr 2018
Edited: Viraj Rodrigo on 28 Apr 2018
Oh yeah btw guys the variables 'x' and 'p' are from a function script that i created before, just wanted to let you know but i dont think it would make any difference :) I still need to know how to use OR statement as stated in the question.
Any help is highly appreciated
Thank you <3

Sign in to comment.

Answers (2)

Ameer Hamza
Ameer Hamza on 28 Apr 2018
Edited: Ameer Hamza on 28 Apr 2018
In this line
x = lower(input('Select colour for Disc1: "Black", "Brown", "Orange", s'));
here you are using lower, whereas, in next line, you are making a comparison with "Black". This condition is failing due to case difference.

John D'Errico
John D'Errico on 28 Apr 2018
Edited: John D'Errico on 28 Apr 2018
While you want to understand the issue of how to use strcmp, a better test is to not do so at all!
So you might use strcmpi, which does a case insensitive test instead.
Better and simpler yet? Use ismember.
if ismember(lower(x), {'black' 'brown' 'orange'})
Do you really want to understand why your code using strcmp failed? Sigh. :)
x = 'Black'
x =
'Black'
x = lower(x)
x =
'black'
strcmp(x,'Black')
ans =
logical
0
Of course they are not the same. You converted the input to all lower case. But then you compared x to an upper case color name.
That is why strcmpi helps.
x
x =
'black'
strcmpi(x,'Black')
ans =
logical
1
But still, USE ISMEMBER.

Categories

Find more on Loops and Conditional Statements 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!