Frustrating for what should be simple… What have I done wrong?

조회 수: 2 (최근 30일)
Jack
Jack 2014년 2월 15일
댓글: Jos (10584) 2014년 2월 16일
Here is an example of some simple code I have written. When I ask the user for a yes/no answer it works for yes but gives an error when they enter no (matrix dimensions do not agree). However it does work if the input is only a y or n. Why is this?
a = 'no';
while a ~= 'yes'
a = input('Do you like the colour red? (yes/no) ——> ','s');
if a == 'yes'
disp('Good its the best colour ever')
elseif a == 'no'
disp('Whats wrong with you?... TRY AGAIN')
else
disp('Thats not an answer, enter y for yes or n for no.')
end
end
THANKS!!

채택된 답변

Paul
Paul 2014년 2월 15일
편집: Paul 2014년 2월 15일
For strings you shouldn't use == to compare but strcmp for case sensitive comparison or strcmpi for not case sensitive. So this code should work for you:
a = 'no';
while ~strcmpi(a,'yes')
a = input('Do you like the colour red? (yes/no) ——> ','s');
if strcmpi(a,'yes')
disp('Good its the best colour ever')
elseif strcmpi(a,'no')
disp('Whats wrong with you?... TRY AGAIN')
else
disp('Thats not an answer, enter y for yes or n for no.')
end
end

추가 답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2014년 2월 15일
편집: Azzi Abdelmalek 2014년 2월 15일
Use
while ~isequal(a,'yes')
You can't compare 'yes' and 'no' using ==, try this
'abc'=='abf'
the result is a comparison character by character. The two strin must have the same number of characters
1 1 0
because the first two element are the same, but not the third. Now if you use
isequal('abc','abf')
the result is
0
because isequal compare the two string, there is no comparison character by character.

Jos (10584)
Jos (10584) 2014년 2월 15일
편집: Jos (10584) 2014년 2월 16일
Another option with strings is to use SWITCH-CASE-END in combination with a WHILE-loop and a BREAK statement. The big advantage using SWITCH over IF is that you can accept different answers
while (1)
a = input('Do you like the colour red? (yes/no) ——> ','s');
switch lower(a)
case {'yes','y','jawohl','yes sir yes','yes i do'}
disp('Good, it''s the best colour ever') % note the double quotes ...
break ; % Breaks out of the infinite while loop
case {'no','n','nope','no way man!','njet','i hate red'}
disp('What''s wrong with you?... TRY AGAIN')
otherwise
disp('That''s not an answer, enter y for yes or n for no.')
end
end
(Edited…Thanks Paul!)
  댓글 수: 2
Paul
Paul 2014년 2월 15일
I think you mean switch instead of which.
Jos (10584)
Jos (10584) 2014년 2월 16일
Of course! ;-) Sorry.

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by