2011-09-01 103 views
2

how to count unique elements of a cell in matlab? 计数字母一个上面的代码将计算字符数的,我喜欢这个在细胞“MATLAB”

[uniqueC,~,idx] = unique(characterCell); %# uniqueC are unique entries in c 
%# replace the tilde with 'dummy' if pre-R2008a 
counts = accumarray(idx(:),1,[],@sum); 

但broblem是细胞数:我的手机包含字母从A到E 。 我想找到'a's'的号码...... 这段代码不会说明有零'e如果它不可用。 简单地将有4个计数,而不是5

 
1 
2 
2 
3 

,而不是

 
1 
2 
2 
3 
0 

如何添加

 
    a=1 
    b=2...... 
+0

好,我有一个= aaabaacaad可能的字符是A到E – pac

回答

4

可以使用ISMEMBER,而不是UNIQUE来解决这个问题:

characterCell = {'a' 'b' 'b' 'a' 'b' 'd' 'c' 'c'}; %# Sample cell array 
matchCell = {'a' 'b' 'c' 'd' 'e'};     %# Letters to count 

[~,index] = ismember(characterCell,matchCell); %# Find indices in matchCell 
counts = accumarray(index(:),1,[numel(matchCell) 1]); %# Accumulate indices 

,你应该得到的counts如下:

counts = 

    2 
    3 
    2 
    1 
    0 

编辑:

如果我正确理解您的评论,这听起来像你想存储或与他们的出现次数一起显示的字母。要做到这一点的方法之一是使用NUM2CELL首先把counts成单元阵列一起将其收集到5×2单元阵列:

>> results = [matchCell(:) num2cell(counts)] 

results = 

    'a' [2] 
    'b' [3] 
    'c' [2] 
    'd' [1] 
    'e' [0] 

或者你可以创建一个字符数组转换counts显示它们使用字符串NUM2STR

>> results = strcat(char(matchCell(:)),':',num2str(counts)) 

results = 

a:2 
b:3 
c:2 
d:1 
e:0 
+0

感谢你的快速回复。 – pac

+0

但它不起作用[uniqueC,〜,idx] = ismember(Allquants {1},{'a','b','c','d','e'}); counts = accumarray(index(:),1,[5 1]) ???错误使用==> cell.ismember 输出参数太多。 – pac

+1

@pac:看看我上面发布的代码。你不能换掉函数名,你必须改变输出的处理方式。 – gnovice

2

调用UNIQUE功能时,您可以将所有可能的字符单元阵列,让你得到每一个的至少一个发生,那么我们只需减去从返回的所有罪名1ACCUMARRAY

例子:

characterCell = {'a' 'b' 'b' 'a' 'b' 'd' 'c' 'c'}; 

allPossibleChars = {'a' 'b' 'c' 'd' 'e'}; %# list of all possible characters 
c = [characterCell allPossibleChars];  %# make sure all chars are represented 
[uniqueC,~,idx] = unique(c); 
counts = accumarray(idx(:),1,[],@sum) - 1; %# subtract one from occurrences 

结果:

>> counts 
counts = 
    2 
    3 
    2 
    1 
    0 
+0

抱歉没有得到您的观点 – pac

+0

@pac:通过添加所有可能的字符(''到'e'),您确保它们都在您的数据中表示。然后我们使用相同的代码来计算每次发生的次数。最后,我们必须从计数中减去1以说明我们最初添加的字符。 – Amro

+0

我想扩展函数,让我们说单元也包含零。如果我使用1'0',在这种情况下,计数的答案将与附加行的零不变= 1相同。如何让它忽略数字? – pac