How to compare string elements within a cell?

1 次查看(过去 30 天)
Trying extract each string from a cell and then make a comparison of each element of that string. Currently this is what i have up until where im getting the error when im trying to compare each element in the if statement. The way i am reading my code the 1st time through my the 1st for loop is assigning input2 as the first indicie of input 'dog'. Then it enters my 2nd for loop looking at each indice of input2 ('dog') then making a comparison in the if statement. Where am i going wrong in this?
input = {'dog','cat','string'};
output = cell(size(input,1),size(input,2));
for k = 1:length(input)
input2 = input{k};
for i = 1:length(input2)
if input2(i) == 'a'||input2(i) == 'e'||input(i) == 'i'||input(i) == 'o'||input(i) == 'u'
out(i) = input2(i) + 3
else
out(i) = input2(i) + 5
end
end
output{k} = out
end

回答(1 个)

Jan
Jan 2015-10-24
编辑:Jan 2015-10-24
You used "input" instead of "input2" in the if condition:
if input2(i) == 'a'||input2(i) == 'e'||input(i) == 'i'||input(i) == 'o'||input(i) == 'u'
better:
if input2(i) == 'a'||input2(i) == 'e'||input2(i) == 'i'||input2(i) == 'o'||input2(i) == 'u'
nicer:
if any(input2(i) == 'aeiou')
A complete function:
inputC = {'dog','cat','string'}; % "input" is a built-in function!
outputC = cell(size(inputC));
for k = 1:numel(inputC) % Safer then LENGTH
inputS = inputC{k};
match = ismember(inputS, 'aeiou');
outputS = inputS + 5;
outputS(match) = inputS(match) + 3;
outputC{k} = outputS;
end

类别

Help CenterFile Exchange 中查找有关 String Parsing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by