Urgent Question about comparing string to a indexed cell array number. (Assignment due tomorrow)

1 view (last 30 days)
I trying to do a problem out my matlab book for school. Basically it asks the user to input a type of shipping which i wrote like this:
type=input('Enter the type of shipping','s');
and later in the program im using the variable type in an if statement like this:
C={'Ground', 'Express', 'Overnight')
for k=1:3
if type == C{k}
disp(yes)
end
when i execute this it will display "yes" for the first iteration of the loop but after the second it will give me an error saying:
Error using == ,Matrix dimensions must agree.

Accepted Answer

Star Strider
Star Strider on 7 Nov 2014
Edited: Star Strider on 7 Nov 2014
I would use the strcmpi function to find the index of the matching shipping method:
shipmthd = 'overnight';
C={'Ground', 'Express', 'Overnight'};
k = find(strcmpi(shipmthd, C));
  2 Comments
Matthew
Matthew on 7 Nov 2014
Hey thanks for your answer. Upon further research i discovered that you cant compare words of different lengths using '==', it will return an error hence why when it would compare Ground with Express an error would display. I ended up using something similar to your answer. Thanks again.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 7 Nov 2014
Hint: Try the ismember() function.
  4 Comments
Image Analyst
Image Analyst on 7 Nov 2014
"type" is a built in command and should not be used for a variable name.
What did you type in? When you incorrectly use == to compare strings, it compares all the elements and all must match. If one does not match, the "if" is not true. Try this with various values for s and observe what happens:
t='abc'
s = 'axa'
t == s
if t == s
fprintf('Match\n');
else
fprintf('No match\n');
end
The proper way is to use string comparison functions like ismember, strcmpi(), strcmp(), etc.
Image Analyst
Image Analyst on 7 Nov 2014
Edited: Image Analyst on 7 Nov 2014
theType = 'Ground';
C={'Ground', 'Express', 'Overnight'};
[~, index] = ismember(theType, C)
You can also use menu instead of input():
C={'Ground', 'Express', 'Overnight'};
button = menu('Shipping Method', C)

Sign in to comment.

Categories

Find more on Data Type Identification 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!