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

 採用された回答

James Tursa
James Tursa 2017 年 4 月 4 日
編集済み: James Tursa 2017 年 4 月 4 日

0 投票

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 件のコメント

Bradley F
Bradley F 2017 年 4 月 4 日
Thanks.
Other than using the strcmpi(y,FavFood) function, would it be possible to use any other operatives?
James Tursa
James Tursa 2017 年 4 月 4 日
編集済み: James Tursa 2017 年 4 月 4 日
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 2017 年 4 月 4 日
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 2017 年 4 月 5 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by