Urgent Question about comparing string to a indexed cell array number. (Assignment due tomorrow)
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Star Strider
on 7 Nov 2014
Edited: Star Strider
on 7 Nov 2014
shipmthd = 'overnight';
C={'Ground', 'Express', 'Overnight'};
k = find(strcmpi(shipmthd, C));
More Answers (1)
Image Analyst
on 7 Nov 2014
Hint: Try the ismember() function.
4 Comments
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
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)
See Also
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!