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 Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

질문:

2017년 4월 4일

댓글:

2017년 4월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by