Hi!
I have a vector with a lot of numbers, for example, A = [9,1,2,5,1,2,5,1,1,5,2,3,1,2,5,1,2,5,4,1,2,5,10]; and I want to remove all the values that are different from 1,2,5,9 or 10. In this case I would want to remove 3 and 4 so A would be
A = [9,1,2,5,1,2,5,1,1,5,2,1,2,5,1,2,5,1,2,5,10];
(I want to apply this to a vector with hundreds of values so I cannot remove that separately, I probably need do do a cycle but its not working)
How can I do this easily?

 채택된 답변

DGM
DGM 2021년 4월 13일
편집: DGM 2021년 4월 13일

1 개 추천

Something like this:
A = [9,1,2,5,1,2,5,1,1,5,2,3,1,2,5,1,2,5,4,1,2,5,10] % input
x = [1,2,5,9,10]; % values to keep
B = A(ismember(A,x))

댓글 수: 4

Adam Danz
Adam Danz 2021년 4월 13일
Also see ismembertol if you're working with floating point values.
Ana Gabriela Guedes
Ana Gabriela Guedes 2021년 4월 14일
Thank you!!
Ana Gabriela Guedes
Ana Gabriela Guedes 2021년 4월 14일
If I have a C vector that corresponds to A and want to remove the correspondents elements in C how can I do it?
So if I have A = [9,1,5,2,3,2] and C = [12,23,41,4,10,6] (for example)
I'll do as you said:
x = [1,2,5,9,]; % values to keep
B = A(ismember(A,x)) % B = [9,1,5,2,2]
and need to end up with an C = [12,23,41,4,6]
How can I remove in C the element that corresponds to the 3 in A?
Adam Danz
Adam Danz 2021년 4월 14일
ismember(A,x) returns a logical index. Use that logical index to remove (or keep) values in both A and B.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2021년 4월 13일

댓글:

2021년 4월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by