开发者

counting letters in a cell "matlab"

how to count unique elements of a cell in matlab? the a above code will count the number of characters in a cell I liked this

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

but the broblem is: my cell contains alphabet letters from a to e. I want to find no of 'a's 'b's...... this code will not tell that there is e.g. zero 'e's if i开发者_JS百科t is not available. simply there will be 4 counts instead of 5

1
2
2
3

and not

1
2
2
3
0

How can I add

     a=1
     b=2......


You can use ISMEMBER instead of UNIQUE to solve this:

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

And you should get the following for counts:

counts =

     2
     3
     2
     1
     0

EDIT:

If I understand your comment correctly, it sounds like you want to store or display the letters together with their number of occurrences. One way to do this is to collect them together into a 5-by-2 cell array by first converting counts into a cell array using NUM2CELL:

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

results = 

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

Or you could create a character array to display them by converting counts to a string using NUM2STR:

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

results =

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


You can append all the possible characters to the cell array when calling the UNIQUE function so that you get at least one occurrence of each, then we simply subtract 1 from all counts returned by ACCUMARRAY.

Example:

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

The result:

>> counts
counts =
     2
     3
     2
     1
     0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜