Effacer les filtres
Effacer les filtres

find ismember on strings

6 vues (au cours des 30 derniers jours)
endystrike
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! :)

Réponse acceptée

Walter Roberson
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))
  1 commentaire
endystrike
endystrike le 12 Mai 2020
thank you so much! :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Particle & Nuclear Physics dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by