Help with if construct error?

1 view (last 30 days)
Pam
Pam on 2 Dec 2014
Answered: dpb on 2 Dec 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

Accepted Answer

Guillaume
Guillaume on 2 Dec 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 Comment
Pam
Pam on 2 Dec 2014
thank you, matlab did suggest strcmp but i wasnt sure how to apply it

Sign in to comment.

More Answers (1)

dpb
dpb on 2 Dec 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

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!