find ismember on strings

8 visualizzazioni (ultimi 30 giorni)
endystrike
endystrike il 12 Mag 2020
Commentato: endystrike il 12 Mag 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! :)

Risposta accettata

Walter Roberson
Walter Roberson il 12 Mag 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))

Più risposte (0)

Categorie

Scopri di più su Particle & Nuclear Physics in Help Center e File Exchange

Prodotti


Release

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by