0

This is my data:

3  3  2
2  4  1
4  1  2
7  5  2
3  4  1
2  6  2
1  5  1

I want somehow to return me that there is 3 duplicates of 1 and 4 duplicates of 2.

I tried find(ismember(e(:,3),set) where set = [1, 2] and length(strfind(e(:,3),'1')) but they not worked... couldn't find anything else

It would be better if it return me it like that

ans = 
      3 1
      4 2
a1204773
  • 6,923
  • 20
  • 64
  • 94

3 Answers3

5

Use unique and histc to count occurrences of elements:

[U, ia, iu] = unique(A(:, 3));   %// Vector of unique values and their indices
counts = histc(iu, 1:numel(U));  %// Count values
res = [counts(:), U];

Example

Let's apply this to your example:

A = [3 3 2; 2 4 1; 4 1 2; 7 5 2; 3 4 2; 2 6 1; 1 5 1];
[U, ia, iu] = unique(A(:, 3));
counts = histc(iu, 1:numel(U));
res = [counts(:), U];

What we get is:

res =
     3     1
     4     2
Eitan T
  • 32,660
  • 14
  • 72
  • 109
5

the best in this case is to use tabulate.

m = tabulate(a(:,3))

m =

1.0000    3.0000   42.8571
2.0000    4.0000   57.1429

[m(:,1), m(:,2)]

ans =

 1     3
 2     4 
zina
  • 144
  • 11
  • 3
    +1: Nice, I didn't know about `tabulate`, but it _is_ worth noting that it requires the Statistics Toolbox installed... Also, instead of writing `[m(:, 1), m(:, 2)]` you can simply write `m(:, 1:2)`. – Eitan T Apr 11 '13 at 16:12
3
data = [3  3  2
        2  4  1
        4  1  2
        7  5  2
        3  4  1
        2  6  2
        1  5  1];

d = data(:,3); %extract relevant data
u = unique(d)'; %find unique list of numbers
D = repmat(d, 1, length(u)); 
s = sum(bsxfun(@eq, u, D)); %count occurences of each number in the unique list
ans = [s', u']

EDIT:

Better answers found here: Determining the number of occurrences of each unique element in a vector

Community
  • 1
  • 1
Dan
  • 45,079
  • 17
  • 88
  • 157