计算列中的重复数字

时间:2013-04-11 13:53:45

标签: matlab

这是我的数据:

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

我想以某种方式告诉我,有3个重复的1个和4个重复的2个。

我尝试了find(ismember(e(:,3),set) set = [1, 2]length(strfind(e(:,3),'1')),但他们没有工作......找不到任何其他内容

如果像那样把它还给我那就更好了

ans = 
      3 1
      4 2

3 个答案:

答案 0 :(得分:5)

使用uniquehistc计算元素的出现次数:

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

实施例

让我们将此应用于您的示例:

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];

我们得到的是:

res =
     3     1
     4     2

答案 1 :(得分:5)

这种情况下最好的是使用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 

答案 2 :(得分: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']

修改

在此处找到更好的答案:Determining the number of occurrences of each unique element in a vector