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

1 次查看(过去 30 天)
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!)

类别

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