フィルターのクリア

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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by