Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count repeating integers in an array

If I have this vector:

x = [1 1 1 1 1 2 2 2 3 4 4 6 6 6 6]

I would like to get the position of each unique number according to itself.

y = [1 2 3 4 5 1 2 3 1 1 2 1 2 3 4]

At the moment I'm using:

y = sum(triu(x==x.')) % MATLAB 2016b and above

It's compact but obviously not memory efficient.

For the pure beauty of MATLAB programming I would avoid using a loop. Do you have a better simple implementation ?

Context:

My final goal is to sort the vector x but with the constraint that a number that appear N times has the priority over another number that has appeared more than N times:

[~,ind] = sort(y);
x_relative_sort = x(ind);
% x_relative_sort = 1   2   3   4   6   1   2   4   6   1   2   6   1   6   1
like image 246
obchardon Avatar asked Jan 07 '19 18:01

obchardon


People also ask

How do you count the number of repeating values in an array Java?

call by int[] repeat=NumberMath. NumberofRepeat(array) for find repeat count. Each location contains how many repeat corresponding value of array... Save this answer.

How do you count the number of repeated numbers in an array in C++?

Function findRepeat(int arr[],int n) takes an array and its length as input and displays the repeated element value and length of repeated elements.


2 Answers

Assuming x is sorted, here's one vectorized alternative using unique, diff, and cumsum:

[~, index] = unique(x);
y = ones(size(x));
y(index(2:end)) = y(index(2:end))-diff(index).';
y = cumsum(y);

And now you can apply your final sorting:

>> [~, ind] = sort(y);
>> x_relative_sort = x(ind)

x_relative_sort =

     1     2     3     4     6     1     2     4     6     1     2     6     1     6     1
like image 71
gnovice Avatar answered Nov 14 '22 04:11

gnovice


If you have positive integers you can use sparse matrix:

[y ,~] = find(sort(sparse(1:numel(x), x, true), 1, 'descend'));

Likewise x_relative_sort can directly be computed:

[x_relative_sort ,~] = find(sort(sparse(x ,1:numel(x),true), 2, 'descend'));
like image 5
rahnema1 Avatar answered Nov 14 '22 04:11

rahnema1