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

6 ビュー (過去 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
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
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
Stephen23 2018 年 11 月 7 日
編集済み: Stephen23 2018 年 11 月 7 日
"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
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 ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by