Reputation: 27
How to change most repeated occurrence element in a vector to one time?
For example I want to convert x = [45 45 65 45 67 65 45 60 70 65 45]
to y = [45 65 67 65 60 70 65]
, here the most frequent element is 45 no need to consider 2nd, 3rd frequent element so unique function wont help for this.
Could anyone suggest a solution for this?
Upvotes: 1
Views: 55
Reputation: 104484
Going with beaker's suggestion, you can use mode
to find the most occurring number, then determine a logical array where we find all of those locations that are to the mode. Now, what we need to do is only remember the first time the mode occurs, so we need to find
the first time we encounter true
in this logical array, and set this location to false
in this array.
Now, we simply index into the original array with the inverse of this array to achieve what you want:
x = [45 45 65 45 67 65 45 60 70 65 45]; %// Your data
%// Find logical array which finds all of the locations equal to the most occurring number
ind = x == mode(x);
%// Set the first time we see this number to false
ind(find(ind,1)) = 0;
%// Index into the data with the opposite to get what we want
y = x(~ind);
We thus get:
y =
45 65 67 65 60 70 65
Upvotes: 1
Reputation: 6187
Use histc
to count the frequency of the elements and then build y
using the most frequent element and those elements that aren't the most frequent.
>> x = [45 45 65 45 67 65 45 60 70 65 45];
>> u = unique(x);
>> [~, ind] = max(histc(x, u));
>> y = [u(ind) x(x ~= u(ind))]
y =
45 65 67 65 60 70 65
If you want to keep the same sorting order as x
but with the most frequent element removed you can build y
with
s = find(u(ind) == x, 1, 'first');
y = [x(1:s) x([u(ind)*ones(1, s) x(s+1:end)] ~= u(ind))]
to give
>> x = [70 65 45 45 65 45 67 65 45 60 70 65 45];
>> u = unique(x);
>> [~, ind] = max(histc(x, u));
>> s = find(u(ind) == x, 1, 'first');
>> y = [x(1:s) x([u(ind)*ones(1, s) x(s+1:end)] ~= u(ind))]
y =
70 65 45 65 67 65 60 70 65
Note: If you are using MATLAB R2014b or later you should use histcounts
instead of histc
.
Upvotes: 1