How to count the total number of occurrences of each digit in cell arrays?
조회 수: 6 (최근 30일)
이전 댓글 표시
Md Shahidullah Kawsar
2018년 11월 7일
편집: pedro antonio solares hernandez
2020년 4월 29일
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에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!