Matrix dimensions must agree - 3 chances loop

Hi, I need help with a code I'm trying to run.
I'm trying to run it so you have 3 chances to guess a string variable correctly, and after the third, it says incorrect, or if any of the guesses are correct then the code ends and just says you have guessed correctly.
The code is shown below that I am using: (The error shown is that Matrix dimensions must agree - the code runs perfectly with correct guesses or when I guess food which has 5 letters)
FavFood=('Pizza');
y=input('What is my favourite Food? ','s');
if y==FavFood
disp('Well done, you guessed correctly');
else x=input('Sorry, you guessed wrong. Try again: ','s');
if x==FavFood
disp('Well done, you guessed correctly');
else z=input('Sorry, you guessed wrong. Try again: ','s');
if z==FavFood
disp('Well done, you guessed correctly');
else disp('Sorry, you ran out of chances.');
end
end
end
Many thanks,
EDIT: typo

 Réponse acceptée

James Tursa
James Tursa le 4 Avr 2017
Modifié(e) : James Tursa le 4 Avr 2017
Your fundamental problem is how you are doing string compares. Do not use the == operator since that is an element-wise operator and is not doing what you think it is doing in your if-tests. Instead, use a function that works with strings, such as strcmpi. E.g.,
if strcmpi(y,FavFood)

4 commentaires

Bradley F
Bradley F le 4 Avr 2017
Thanks.
Other than using the strcmpi(y,FavFood) function, would it be possible to use any other operatives?
James Tursa
James Tursa le 4 Avr 2017
Modifié(e) : James Tursa le 4 Avr 2017
If you want to be case sensitive, you could use "strcmp" or "isequal". Or you could use a combination of the "upper" function with these for your test to remain case insensitive.
Bradley F
Bradley F le 4 Avr 2017
Hi,
Yeah, I used the "upper" function to deal with the case sensitive issue. I was just wondering if I could deal with the problem without using the "strcmpi" function?
If not, it's fine, but I'm just curious.
Cheers
James Tursa
James Tursa le 5 Avr 2017
Well, you could always write your own function. It would have to check to see that both arguments are strings and both have the same dimensions, and then something like all(upper(arg1)==upper(arg2)) to check if all the individual letters match.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Tags

Aucun tag saisi pour le moment.

Community Treasure Hunt

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

Start Hunting!

Translated by