Clear Filters
Clear Filters

How to count the total number of occurrences of each digit in cell arrays?

4 views (last 30 days)
Suppose I have a cell array
C = {[1; 4; 7]; [2; 5; 8; 9]; [3; 4]};
c{:}
ans =
1
4
7
ans =
2
5
8
9
ans=
3
4
% where any digit won't repeat in the individual cell.
% There are 4 stages in this cell array.
% first stage elements are 1, 2, 3
% second stage elements are 4, 5, 4
% third stage elements are 7,8
% fourth stage elements are 9
I need to count the total number of occurrences of each digit in stage 2. Expected output:
Digit | Number of occurrences
4 2
5 1
  1 Comment
Guillaume
Guillaume on 7 Nov 2018
Your concept of stage is badly thought. You would be much better off storing stages as element of the cell array rather than scattering them across the elements. So:
c = {[1 2 3], [4 5 4], [7 8], 9]}
As it is you will have to programmatically convert your existing cell array into the above to do your histogram any way.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 7 Nov 2018
>> C = {[1; 4; 7]; [2; 5; 8; 9]; [3; 4]};
>> V = cellfun(@(v)v(2),C);
>> U = unique(V);
>> N = histc(V,U);
>> [U,N]
ans =
4 2
5 1
  3 Comments
Stephen23
Stephen23 on 7 Nov 2018
Edited: Stephen23 on 7 Nov 2018
"What if I also want to include stage 3 and stage 4?"
Method one: read Guillaume's comment and follow that advice. Then you can use a simple loop:
% Your data:
C = {[1;4;7]; [2;5;8;9]; [3;4]}
% Convert cell array:
X = cellfun(@(v)1:numel(v),C,'uni',0);
X = accumarray([X{:}].',vertcat(C{:}),[],@(v){v})
for k = 1:numel(X)
U = unique(X{k});
N = histc(X{k},U);
[U,N]
end
Giving:
ans =
1 1
2 1
3 1
ans =
4 2
5 1
ans =
7 1
8 1
ans =
9 1
Method two: alternatively you could use nested loops and a cellfun call to check the length of the cell contents. The use a loop:
C = {[1;4;7]; [2;5;8;9]; [3;4]}
L = cellfun('length',C)
for k = 1:max(L)
V = cellfun(@(v)v(k),C(L>=k));
U = unique(V);
N = histc(V,U);
[U,N]
end
Giving:
ans =
1 1
2 1
3 1
ans =
4 2
5 1
ans =
7 1
8 1
ans =
9 1
pedro antonio solares hernandez
Edited: pedro antonio solares hernandez on 29 Apr 2020
Hello!; it's posible to compute with this example the elements from rows? In this example, the results coming from the columns.
For example, if i have the array C = {[1,1,7,2]; [2,5,8,6]; [3,4,2,2,4,3]}, ill like to have the next result:
row 1:
1-> 2
2-> 1
7->1
row 2:
2-> 1
5-> 1
6-> 1
8-> 1
row 3:
2-> 2
3-> 2
4-> 2

Sign in to comment.

More Answers (0)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!