delete elements from the given array

조회 수: 11 (최근 30일)
Oksi Moon
Oksi Moon 2020년 12월 1일
댓글: Stephan 2020년 12월 1일
for example. an array X is given, which is X=[1,2,3,4,5,6] how to delete all even numbers of this array except the last even number(6)? In other words, how to make this array look like X=[1,3,5,6]?

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 12월 1일
Try this
X=[1,2,3,4,5,6];
idx = find(mod(X,2)==0);
X(idx(1:end-1)) = []
  댓글 수: 2
Oksi Moon
Oksi Moon 2020년 12월 1일
Thank you very much!
Stephan
Stephan 2020년 12월 1일
X=[1,2,3,4,5,6,7]
idx = find(mod(X,2)==0);
X(idx(1:end-1)) = []
results in:
X =
1 2 3 4 5 6 7
X =
1 3 5 6 7
you stated:
"...what if I have 7 elements [1,2,3,4,5,6,7] and I still need to get [1,3,5,6]. i need to leave the last even number. not just the last number"

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

추가 답변 (1개)

Stephan
Stephan 2020년 12월 1일
X(2:2:end-1) = []
  댓글 수: 2
Oksi Moon
Oksi Moon 2020년 12월 1일
thank you! what if I have 7 elements [1,2,3,4,5,6,7] and I still need to get [1,3,5,6]. i need to leave the last even number. not just the last number
Stephan
Stephan 2020년 12월 1일
편집: Stephan 2020년 12월 1일
X=[1,2,3,4,5,6,7]
idx = find(mod(X,2)==0,1,'last');
X(idx+1:end) = [];
X(2:2:idx-1) = []
gives:
X =
1 2 3 4 5 6 7
X =
1 3 5 6

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by