如何仅保留系列相同元素的上层元素并删除其他元素

时间:2012-11-22 05:17:05

标签: matlab

以下矩阵:

A = [ -1 1 -1 1 -1 1 0 0 0 0 -1 1 0 0 -1 1 -1 1 0 0 ]

会是这样的:

A = [ -1 1           0 0 0 0 -1 1 0 0 -1 1      0 0 ]

1 个答案:

答案 0 :(得分:1)

有趣的小问题。我相信这有效:

A = [-1 1 -1 1 -1 1 0 0 0 0 -1 1 0 0 -1 1 -1 1 0 0]; %# Set up an example vector
I1 = [1, 1, A(1:end-2) - A(3:end)]; %# Index all repetitions of sets of two using zeros
I1(A == 0) = 1; %# Ensure our index doesn't remove any of the 0's from the original vector
Soln = A(I1 ~= 0); %# Obtain solution using nonzero entries of the index