필터 지우기
필터 지우기

finding index of several values within a vector efficiently

조회 수: 2 (최근 30일)
Jimmian Lin
Jimmian Lin 2012년 12월 2일
I am trying to find the index of 'several' values within an array/vector. For instance, I have a vector [1 2 5] and matrix X=[1 5 4 3 2]. I want it to return [1 5 2]. I could write a for loop that finds each values in that vector such as find(X==1), then find(X==2) ..., but I was hoping there is a vectorized way to do this. Thanks.

채택된 답변

the cyclist
the cyclist 2012년 12월 2일
v = [1 2 5];
X = [1 5 4 3 2];
[tf loc] = ismember(v,X);
"loc" is the vector you want.

추가 답변 (1개)

Matt Fig
Matt Fig 2012년 12월 2일
편집: Matt Fig 2012년 12월 2일
idx = [1 2 5];
X = [1 5 4 3 2];
vals = X(idx) % linear indexing.
  댓글 수: 2
the cyclist
the cyclist 2012년 12월 2일
If I am interpreting Jimmian's question correctly, this method only gives the correct answer to the example because of a numerical coincidence. For example, if
X = [0 0 0 0 0 1 5 4 3 2]
then I think he wants the output to be
loc = [6 10 7]
and not
[0 0 0].
Matt Fig
Matt Fig 2012년 12월 2일
편집: Matt Fig 2012년 12월 2일
Exactly how I interpreted your answer when I read it (works because of a coincidence).
:-)
It would be nice to have an example from OP that is unambiguous......

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by