0

Could someone help me to create a function in Matlab?. I have an array with 40 elements where some elements are duplicate.

I need to create a function that counts the duplicate values in the array and print like this i.e:

Number 21 repeats 4 time(s)
Number 25 repeats 1 time(s)
Number 40 repeats 3 time(s) etc.

Thank you in advance. I have been trying for hours.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 2
    If you add the code from one of your previous attempts, we could use that as a base to help you identify what went wrong and how to fix it. – Bryan Herbst Jun 01 '15 at 19:45
  • Hi , I cannot figure it out how to do so you can provide a sample array that will fix the problem – user3070259 Jun 01 '15 at 20:05
  • check out [this](http://www.mathworks.com/matlabcentral/answers/19042-finding-duplicate-values-per-column) – dlavila Jun 01 '15 at 20:33

2 Answers2

4

You can use unique and histc:

x = [1 3.5 4 3.5 4 9 7 9 4 2]; %// example data
unique_values = unique(x(:));
counts = histc(x(:), unique_values);

The results for this example are:

unique_values.' =
    1.0000    2.0000    3.5000    4.0000    7.0000    9.0000
counts.' =
     1     1     2     3     1     2

Or use unique and accumarray:

x = [1 3.5 4 3.5 4 9 7 9 4 2]; %// example data
[unique_values, ~, labels] = unique(x(:));
counts = accumarray(labels, 1);
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
-1

You can try this:

array = randi(40,1,40)
array_labels = unique(array)
% counter(length(array_labels))=0
counter = zeros(1,length(array_labels))
for j=1:length(array_labels)
    for i=1:40
        if array(i)==array_labels(j)
           counter(j) = counter(j) + 1;
        end
    end
end
counter
final = horzcat(array_labels',counter')
sum(counter)
Adolfo Correa
  • 813
  • 8
  • 17
  • 1
    Also, the other answer is way better. You should try not use loops if they are not necessary. The other answer provides a much more succinct and efficient solution – Matt Jun 01 '15 at 22:53