开发者

matlab - removing elements with low frequency in an array

If you have a MATLAB array such as the below:

A = [1,1,1,1,2,2,2,2,3,3,3,4,4,5]

I want to be able to filter this array so that elements which have a low frequency are removed.

In other words, is there an easy开发者_开发百科 way to remove elements in the array which have a certain low frequency for example <= than 2?

In this case:

The result would be:

[1,1,1,1,2,2,2,2,3,3,3]

Cheers


I'd probably do it somehow like this (hope the syntax is good :))

function array= ClearElementsWithLowOccurence(array,minimalFrequency)
elements = unique(array);
indecesToRemove = [];
for i = 0:length(elements)
   indeces = find(array==elements(i));
   if (length(indeces) < minimalFrequency)
      indecesToRemove = [indecesToRemove indeces];
   end;
end;
array(indecesToRemove) = [];


Here's a quick way. A does not need to be sorted, the numbers can be anything.

A = [1,1,1,1,2,2,2,2,3,3,3,4,4,5];

%# count the numbers in A (use unique so that the array
%# remains at a decent size even if the values are very different)
[uniqueEntries,~,idx] = unique(A);
counts = histc(idx,1:max(idx));

%# remove all the numbers whose count is less or equal than two
A(ismember(A,uniqueEntries(counts<=2))) = []


Considering that the problem you've posted does not belong to a single domain, but can be encountered almost everywhere, i'll go with pseudocode. I hope thats not too much of a problem/irritation.

here's what you can do

  1. Take variables

    • LIMIT: the minimum frequency required for an element to survive (2 in this case)
    • ELEMENT: the value of the present array element
  2. Now, for-each (new) ELEMENT encountered, do the following:

    • check the element LIMIT ahead of ELEMENT
    • if it equals ELEMENT, this value will be retained, and continue in the same way to the next value (now ELEMENT) until the array has been fully traversed.
    • If not, remove all occurrences of this value., and again continue.....

    Finally, you end up with the required array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜