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

4 views (last 30 days)
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!!

Accepted Answer

Paul
Paul on 15 Feb 2014
Edited: Paul on 15 Feb 2014
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

More Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 15 Feb 2014
Edited: Azzi Abdelmalek on 15 Feb 2014
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) on 15 Feb 2014
Edited: Jos (10584) on 16 Feb 2014
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!)

Products

Community Treasure Hunt

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

Start Hunting!