find ID's of repeated values in array

조회 수: 2 (최근 30일)
Kim Arnold
Kim Arnold 2021년 9월 17일
댓글: Kim Arnold 2021년 9월 17일
Let's say I have 2 arrays, one longer t1 (1x15 double) and a shorter one t2(1x8 double) and I tried to find the indices of t1 in the t2 as follows:
t1=[1,2,3,3,3,4,5,6];
t2=[1,1.5,2,3,4,5,6,7,8,9,9.5,19,25,31,42];
IDt1_int2=ismember(t2,t1)
>> ismember(t2,1)
ans =
1×15 logical array
1 0 1 1 1 1 1 0 0 0 0 0 0 0 0
but what I acutally wanted is something like this
IDt1_int2=find(ismember(t2,t1));
find(ismember(t2,t1))
ans =
1 3 4 5 6 7
but what i want it to give as an ouput is an array of IDs which considers the numbeer 3 in my t1 three times like this
[1 3 4 4 4 5 6 7];
Could you help here? Thank you
  댓글 수: 2
Stephen23
Stephen23 2021년 9월 17일
편집: Stephen23 2021년 9월 17일
The simple MATLAB approach:
t1 = [1,2,3,3,3,4,5,6];
t2 = [1,1.5,2,3,4,5,6,7,8,9,9.5,19,25,31,42];
[~,idx] = ismember(t1,t2) % note the order!
idx = 1×8
1 3 4 4 4 5 6 7
Don't waste your time calling ISMEMBER multiple times in an inefficient loop.
Kim Arnold
Kim Arnold 2021년 9월 17일
Thank you very much Stephen.
Yes I tried it with
[~,idx] = ismember(t2,t1)
which was the wrong order to give the inputs.

댓글을 달려면 로그인하십시오.

채택된 답변

Simon Chan
Simon Chan 2021년 9월 17일
You may use a for loop as follows:
idx = zeros(1,length(t1));
for k = 1:length(t1)
idx(k) = find(ismember(t2,t1(k)));
end
  댓글 수: 1
Kim Arnold
Kim Arnold 2021년 9월 17일
Dear Simon,
Thanks that works perfectly fine!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

KSSV
KSSV 2021년 9월 17일
[c,ia] = ismember(t2,t1)
  댓글 수: 2
Kim Arnold
Kim Arnold 2021년 9월 17일
편집: Kim Arnold 2021년 9월 17일
thank you, but this does not give me what I want as I described above it just gives me besides the logical also the location. but what I want is an output as: [1 3 4 4 4 5 6 7]; where it tells me that the number 3 of t1 is at position 4 in t2, three times because i need later to extract those positions again for plotting.
Kim Arnold
Kim Arnold 2021년 9월 17일
What you wrote was correct when it was first t1 and then t2 :) however, thank you for the input
[c,ia] = ismember(t1,t2)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Language Fundamentals에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by