Error with if elseif statements

조회 수: 13 (최근 30일)
Bree
Bree 2016년 11월 30일
댓글: Vaibhav Sharma 2018년 2월 18일
My program is set up to ask the user for an input variable, as follows:
GOAL=input('WHAT IS YOUR GOAL?(FIT=FITNESS, FB=FAT BURN, N=NEITHER): ','s');
Then, I wrote an if, elseif statement written as:
if GOAL==('FIT')
I wrote the same thing for if GOAL==('FB') and if GOAL==('N'), and each is followed by functions to be executed for whichever the user chooses.
The error message that I am getting says:
Error using == Matrix dimensions must agree.
Am I approaching it wrong? Anything helps, thanks.
  댓글 수: 1
Vaibhav Sharma
Vaibhav Sharma 2018년 2월 18일
I get the exact message for a different function of question answering

댓글을 달려면 로그인하십시오.

채택된 답변

bio lim
bio lim 2016년 11월 30일
I suggest you to use strcmp
GOAL=input('WHAT IS YOUR GOAL?(FIT=FITNESS, FB=FAT BURN, N=NEITHER):\n ','s');
if strcmp(GOAL, 'FITNESS')
sprintf('GOOD')
elseif strcmp(GOAL, 'FB')
sprintf('ALSO GOOD')
else strcmp(GOAL, 'N')
sprintf('WHAT YOU SEEK HUMAN')
end
  댓글 수: 2
Bree
Bree 2016년 11월 30일
Thank you!!!
Vaibhav Sharma
Vaibhav Sharma 2018년 2월 18일
I too am forced to thank you for making me aware of that function

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Daniel kiracofe
Daniel kiracofe 2016년 11월 30일
In matlab, strings are arrays of characters. Two strings with different lengths have different array dimensions. e.g.
'dog' is a 3x1 character array.
'bird' is a 4x1 character array
So something like this
if ('dog' == 'bird')
will give an error because you are trying to compare a 3x1 array with a 4x1 array, and to compare arrays they must have the same length.
try the strcmp() function instead. i.e
if strcmp(GOAL, 'fit')
  댓글 수: 2
Bree
Bree 2016년 11월 30일
You guys are so smart, thanks!
Vaibhav Sharma
Vaibhav Sharma 2018년 2월 18일
Really True

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by