필터 지우기
필터 지우기

Index multiple elements in a vector using logical indexing

조회 수: 3 (최근 30일)
Rob
Rob 2011년 3월 28일
답변: Vasileios Siomos 2017년 3월 25일
Hi, I want to use logical indexing to "grap" some elements from a vector. Normally if you're only looking for a single element, you could use the "find" function, for example:
A = [1 2 3 4 5 6];
B = 2;
C = [5 6 7 8 9 0]
D = C(find(A==B));
or use something like: D = C(A==B);
But now I am interested in finding multiple elements in A. So B becomes a vector in this case. For example:
A = [1 2 3 4 5 6];
B = [2 4];
C = [5 6 7 8 9 0]
I thought I could do something simular as in the upper case, by writing something like:
D = C(A==B). But apparently this does noet work.
Can anyone help me? Thanks a lot in advance!
  댓글 수: 2
Sean de Wolski
Sean de Wolski 2011년 3월 28일
Very well written question, you get a vote!
Matt Tearle
Matt Tearle 2011년 3월 28일
Indeed! Good question, and good answers. A good community exchange all round!
(It was a Q&A of two halves, the comment with the most votes won, but MATLAB Answers was the real winner on the day. Ahhh, my cliche-o-matic is stuck...)

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

채택된 답변

Sean de Wolski
Sean de Wolski 2011년 3월 28일
Oleg's way is probably faster, but also:
D = C(any(bsxfun(@eq,A.',B),2))
  댓글 수: 1
Rob
Rob 2011년 3월 28일
Thanks a lot to both of you.
I was not aware of the "ismember" function, but this works indeed.
Thanks!

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

추가 답변 (2개)

Oleg Komarov
Oleg Komarov 2011년 3월 28일
For comparison with multiple elements:
D = C(ismember(A,B))
Also, avoid to use find when you don't need the coordinates.

Vasileios Siomos
Vasileios Siomos 2017년 3월 25일
This is an awesome trick thanks a bunch guys

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by