필터 지우기
필터 지우기

Help with if construct error?

조회 수: 1 (최근 30일)
Pam
Pam 2014년 12월 2일
답변: dpb 2014년 12월 2일
I created this script for the user to input either English, Literature, Astronomy or History and in the command window it will accept English and History but not the other two, any help?
x=input('Please choose of of the following electives\n English\n History\n Astronomy\n Literature\n: ','s');
if x=='English'
disp('English has been selected.');
elseif x=='History'
disp('History has been selected.');
elseif x=='Astronomy'
disp('Astronomy has been selected.');
elseif x=='Literature'
disp('Literature has been selected.');
else
disp('Invalid choice selected.');
end

채택된 답변

Guillaume
Guillaume 2014년 12월 2일
Use strcmp (or strcmpi) to compare strings, not ==
if strcmp(x, 'English')
...
Another option would be to use a switch statement instead of if
switch x
case 'English'
...
case 'History'
...
...
end
  댓글 수: 1
Pam
Pam 2014년 12월 2일
thank you, matlab did suggest strcmp but i wasnt sure how to apply it

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

추가 답변 (1개)

dpb
dpb 2014년 12월 2일
When you enter a selection past the first two the length of the comparison string changes--by happenstance "English" and "History" are both seven characters in length. The == operator in Matlab returns an array of length of the input and a T|F comparison element-by-element. The if...elseif...end clause is executed sequentially and it appears Matlab is keeping some internal variable that is holding the intermediate result of the first comparison.
The general rule is to avoid this by using the string functions instead --
if strfind(s,'English')
...
etc., etct., ...
A CASE structure might be simpler than the nested elseif but for convenience of your users, I'd suggest making this a selection via
doc listdlg
Far less coding required and more convenient in that typo's and the like are removed.
if x=='English'
x=input('Please choose of of the following electives\n English\n History\n Astronomy\n Literature\n: ','s');
if all(x=='English')
disp('English has been selected.');end
if all(x=='History')
disp('History has been selected.');end
if all(x=='Astronomy')
disp('Astronomy has been selected.');end
if all(x=='Literature')
disp('Literature has been selected.');end
else
disp('Invalid choice selected.');
end

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by