How to count the total number of occurrences of each digit in cell arrays?
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
Guillaume
2018-11-7
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.
采纳的回答
Stephen23
2018-11-7
>> 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 个评论
Stephen23
2018-11-7
编辑:Stephen23
2018-11-7
"What if I also want to include stage 3 and stage 4?"
% 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
2020-4-29
编辑:pedro antonio solares hernandez
2020-4-29
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!