Frustrating for what should be simple… What have I done wrong?
Afficher commentaires plus anciens
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!!
Réponse acceptée
Plus de réponses (2)
Azzi Abdelmalek
le 15 Fév 2014
Modifié(e) : Azzi Abdelmalek
le 15 Fév 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)
le 15 Fév 2014
Modifié(e) : Jos (10584)
le 16 Fév 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!)
2 commentaires
Paul
le 15 Fév 2014
I think you mean switch instead of which.
Jos (10584)
le 16 Fév 2014
Of course! ;-) Sorry.
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!