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

6 Ansichten (letzte 30 Tage)
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 Kommentar
Guillaume
Guillaume am 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 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 Kommentare
Stephen23
Stephen23 am 7 Nov. 2018
Bearbeitet: Stephen23 am 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
Bearbeitet: pedro antonio solares hernandez am 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by