find ismember on strings

14 ビュー (過去 30 日間)
endystrike
endystrike 2020 年 5 月 12 日
コメント済み: endystrike 2020 年 5 月 12 日
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! :)

採用された回答

Walter Roberson
Walter Roberson 2020 年 5 月 12 日
[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 件のコメント
endystrike
endystrike 2020 年 5 月 12 日
thank you so much! :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by