How I can extract data from a vector based on index

조회 수: 18 (최근 30일)
Rita
Rita 2016년 6월 3일
답변: Stephen23 2022년 4월 11일
I have an index and a vector I would like to have data from the vector which is not in the index!For example
A=[5 3 7 8 89 6]
index=[2 3 4 5]
Now I want to have B as my answer B=[5 6] Thanks!

채택된 답변

Roger Stafford
Roger Stafford 2016년 6월 3일
편집: Roger Stafford 2016년 6월 3일
B = A(setdiff((1:length(A)).,index(:)));
or if you're sure A and index are row vectors just
B = A(setdiff(1:length(A),index));

추가 답변 (2개)

Stephen23
Stephen23 2022년 4월 11일
A simple and efficient approach:
A = [5,3,7,8,89,6];
index = [2,3,4,5];
B = A;
B(index) = []
B = 1×2
5 6

Johanna
Johanna 2022년 2월 21일
I looking for the opposite command of setdiff. That is, taking the example from above, I want the answer to be B=[3 7 8 89].
In particular I'm actually looking for the mean of the values mentioned in my index vector. I tried mean(A(index)), however, this does not work.
I guess it has to be something like mean(A(setequal(1:length(A),index))), however, setequal does not exist. Thanks!
  댓글 수: 2
Stephen23
Stephen23 2022년 2월 21일
" I want the answer to be B=[3 7 8 89]."
A = [5,3,7,8,89,6];
index = [2,3,4,5];
B = A(index)
B = 1×4
3 7 8 89
Janiece Jackson
Janiece Jackson 2022년 4월 11일
Thank you so much for this answer!!!

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

카테고리

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