find ismember on strings

조회 수: 17 (최근 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 CenterFile Exchange에서 Loops 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