Create a row vector comparing strings in a for loop
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Lorenzo Amedeo
el 18 de En. de 2023
Comentada: Lorenzo Amedeo
el 19 de En. de 2023
I have two string arrays with different sizes and assume that the second one (s2) has a variable size.
I need to create a vector (index) that contains only the indices where 'strcmpi' returns the logical value 1. It works if 's2' contains only strings present in 's1', otherwiswe the following error occurs. I think that's because I am assigning to 'index' the size of 'k' but there will be only 3 logical value = 1, but I don't know how to fix it.
Any help would be appreciated. Thanks.
s1 = { 'FMO1','FMO2','FMO3','FMO4', 'BAO1', 'BAO2', 'BAO3', 'BAO4'};
s2 = {'mean','FMO1','BAO4','FMO2'};
for k = 1 : length(s2)
compare = strcmpi(s2{k},s1);
index(k) = find(compare==1)
end
Respuesta aceptada
Davide Masiello
el 18 de En. de 2023
index = [];
s1 = { 'FMO1','FMO2','FMO3','FMO4', 'BAO1', 'BAO2', 'BAO3', 'BAO4'};
s2 = {'mean','FMO1','BAO4','FMO2'};
for k = 1 : length(s2)
compare = strcmpi(s2{k},s1);
index = [index,find(compare==1)];
end
index
This way, even if any of the entry in s2 appears several times in s1 you should be ok.
2 comentarios
Más respuestas (1)
Stephen23
el 18 de En. de 2023
The simple MATLAB approach:
s1 = { 'FMO1','FMO2','FMO3','FMO4', 'BAO1', 'BAO2', 'BAO3', 'BAO4'};
s2 = {'mean','FMO1','BAO4','FMO2'};
X = contains(s1,s2)
Y = find(X) % optional
Ver también
Categorías
Más información sobre Loops and Conditional Statements 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!