find ismember on strings
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
endystrike
le 12 Mai 2020
Commenté : endystrike
le 12 Mai 2020
Hello everyone,
I have 2 string arrays and I want to know the position of each element of the 1st array into the 2nd one...
I tried to code this but cannot understand why it's not working...
p1_i = ["GOOGL","AAPL","CSCO","INTC","MSFT","NVDA","ADBE","EA","AMZN"];
p2_i = ["SPY","TLT","IEF","GLD","DBC"];
all_i = unique(deblank([p1_i,p2_i]));
if I do
disp(all_i);
I get
>> disp(all_i)
"AAPL" "ADBE" "AMZN" "CSCO" "DBC" "EA" "GLD" "GOOGL" "IEF" "INTC" "MSFT" "NVDA" "SPY" "TLT"
The point is that if I try to understand which index has each string of p1_i and p2_i into all_i, I don't get them into the correct order...
find(ismember(all_i,p1_i))
>> find(ismember(all_i,p1_i))
ans =
1.00 2.00 3.00 4.00 6.00 8.00 10.00 11.00 12.00
I solved using a "for" cycle so that the find(ismember(x)) is applied to each element of "p1_i", but would it be possible without the "for" cycle?
p1_i_idx = zeros(size(p1_i));
for k=1:length(p1_i_idx)
p1_i_idx(k) = find(ismember(all_i,p1_i(k)));
end
disp(p1_i_idx);
>> disp(p1_i_idx)
8.00 1.00 4.00 10.00 11.00 12.00 2.00 6.00 3.00
Thanks a lot everyone! :)
0 commentaires
Réponse acceptée
Walter Roberson
le 12 Mai 2020
[wasfound, idx] = ismember(p1_i, all_i);
idx is 0 in the locations that wasfound is false, and otherwise p1_i(K) == all_i(idx(K))
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!