delete elements from the given array

10 次查看(过去 30 天)
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 个评论
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