How to compare string elements within a cell?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (1)
Jan
el 24 de Oct. de 2015
Editada: Jan
el 24 de Oct. de 2015
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
0 comentarios
Ver también
Categorías
Más información sobre String Parsing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!