在Matlab中查找向量中已删除的元素

时间:2019-03-12 18:24:56

标签: matlab vector repeat pruning

我有一个反复迭代的过程,它随机修剪一个巨大的整数向量,我想找出每次迭代之间要删除的元素。这个向量有很多重复,使用ismember()和setdiff()并没有太大帮助。

例如,如果X = [1,10,8,5,10,3,5,2]:

step 0: X = 1,10,8,5,10,3,5,2
step 1: X = 1,10,8,10,3,5,2 (5 is removed)
step 2: X = 1,10,8,3,2 (10 and 5 are removed)
step 3: X = 10,8,3,2 (1 is removed)
step 4: X = 2 (10, 8 and 3 are removed)
step 5: X = [] (2 is finally removed)

我的目标是找到在每个步骤中删除的元素(即5个,然后10个和5个,依此类推)。我可能会在步骤之间使用hist(X, unique(X))来找到一个过于复杂的解决方案,但我认为在matlab中存在一个更为优雅(且更便宜!)的解决方案。

1 个答案:

答案 0 :(得分:3)

我想到了通过减去两个值并迭代不同的值从输出中恢复输入的想法,然后将这些值作为已删除元素的索引。

% Input.
X = [1, 10, 8, 5, 10, 3, 5, 2];

% Remove indices for the given example.
y = { [4], [4 6], [1], [1 2 3], [1] };

% Simulate removing.
for k = 1:numel(y)

  % Remove elements.
  temp = X;
  temp(y{k}) = [];

  % Determine number of removed elements.
  nRemoved = numel(X) - numel(temp);

  % Find removed elements by recovering input from output.
  recover = temp;
  removed = zeros(1, nRemoved);
  for l = 1:nRemoved
    tempdiff = X - [recover zeros(1, nRemoved - l + 1)];
    idx = find(tempdiff, 1);
    removed(l) = X(idx);
    recover = [recover(1:idx-1) X(idx) recover(idx:end)];
  end

  % Simple, stupid output.
  disp('Input:');
  disp(X);
  disp('');
  disp('Output:');
  disp(temp);
  disp('');
  disp('Removed elements:');
  disp(removed);
  disp('');
  disp('------------------------------');

  % Reset input.
  X = temp;

end

给定示例的输出:

Input:
    1   10    8    5   10    3    5    2

Output:
    1   10    8   10    3    5    2

Removed elements:
 5

------------------------------
Input:
    1   10    8   10    3    5    2

Output:
    1   10    8    3    2

Removed elements:
   10    5

------------------------------
Input:
    1   10    8    3    2

Output:
   10    8    3    2

Removed elements:
 1

------------------------------
Input:
   10    8    3    2

Output:
 2

Removed elements:
   10    8    3

------------------------------
Input:
 2

Output:
[](1x0)

Removed elements:
 2

------------------------------

这是一个合适的解决方案,还是我缺少一些(显而易见的)低效率?