Filter löschen
Filter löschen

Help with if construct error?

1 Ansicht (letzte 30 Tage)
Pam
Pam am 2 Dez. 2014
Beantwortet: dpb am 2 Dez. 2014
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

Akzeptierte Antwort

Guillaume
Guillaume am 2 Dez. 2014
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 Kommentar
Pam
Pam am 2 Dez. 2014
thank you, matlab did suggest strcmp but i wasnt sure how to apply it

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

dpb
dpb am 2 Dez. 2014
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

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by