OR statement in MATLAB issue

조회 수: 2 (최근 30일)
Viraj Rodrigo
Viraj Rodrigo 2018년 4월 28일
편집: John D'Errico 2018년 4월 28일
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
Viraj Rodrigo
Viraj Rodrigo 2018년 4월 28일
편집: Viraj Rodrigo 2018년 4월 28일
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

댓글을 달려면 로그인하십시오.

답변 (2개)

Ameer Hamza
Ameer Hamza 2018년 4월 28일
편집: Ameer Hamza 2018년 4월 28일
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 2018년 4월 28일
편집: John D'Errico 2018년 4월 28일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by