从向量中删除重复的零

时间:2013-11-28 04:45:12

标签: matlab

假设我有这个载体:

A=[0 0 0 400 600 1000 1400 0 0 0 0 0 0 0 600 400 100 1000 0 0 0 0 400 600 1000 0 0];

如何在非零之间将重复的零压缩到最多两个零,并且在末尾只允许一个零?输出应为:

B=[0 400 600 1000 1400 0 0 600 400 100 1000 0 0 400 600 1000 0];

2 个答案:

答案 0 :(得分:2)

明显的目标是将非零之间出现的零序列压缩到最多只有两个零,并且对于向量末端的重复零点仅压缩一个零。问题中给出的示例输入/输出如下。

输入:

A = [0 0 0 400 600 1000 1400 0 0 0 0 0 0 0 600 400 100 1000 0 0 0 0 400 600 1000 0 0];

输出:

B0 = [0 400 600 1000 1400 0 0 600 400 100 1000 0 0 400 600 1000 0];

这可以通过以下陈述来完成:

dx = diff(A==0);
extraZeros = (A==0) & ~([dx==-1 0] | [0 dx==1]);
B = A(~extraZeros)
B =
  Columns 1 through 7
       0         400         600        1000        1400           0           0
  Columns 8 through 14
     600         400         100        1000           0           0         400
  Columns 15 through 17
     600        1000           0
isequal(B,B0)
ans =
     1

确保A行向量,否则先转置输入(A=A.';)。

答案 1 :(得分:0)

如果要查找最重复数字的最后一个索引,可以执行以下操作:

% using histc count all numbers
uniqueA = unique(A);
n = histc( A, unique(A) );


% find most repeated number based on hist output
[C,I] = max(n);
mostRepeatedNumber = uniqueA(I(1));

lastIndexOfMostRepeatedNumber = find(A == mostRepeatedNumber, 1, 'last');

要查找字符串中最后一个零的索引,您可以执行以下操作:

zerosInA = A == 0;
lastZeros = find(diff(zerosInA) == -1);
% lastZeros = 3    14    22
% NOTE: it wont detect the last zero. But you can easily check whether last element
% is zero or not, i.e. A(end) == 0.
相关问题