Reputation:
If I have an mxn cell array whose elements are either an integer or a vector of integers, how could I count how many times a particular integer occurs in the entire cell array? The integer could occur individually in a cell or in a vector in a cell.
My cells will look like this :
cell = { 1,2,3,4,5; [6,7,1], 2,7,8,9; 1,3,9,10, [1,2] }
Upvotes: 0
Views: 228
Reputation: 3177
A simple cellfun()
will help you.
Such function will perform a given function (ismember()
in our case) on every cell in a given cell array.
Let's say we want to look for 1
:
result=cellfun(@(x)ismember(1,x),cell);
and result
will be a binary (boolean) matrix with 1 (true
) in position (i,j) if cell{i,j}
contains 1. To count how many items there are is enough to sum all the 1 in result
:
numberOfItems=sum(result(:));
In our case then, result
will have the form:
1 0 0 0 0
1 0 0 0 0
1 0 0 0 1
and that is correct because 1 appears in cell{1,1}
, cell{3,1}
and also in the arrays that are in cell{2,1}
and cell{3,5}
. Now we can count the ones in result
, or simply sum the entire matrix (its only values are 0s and 1s) to get numberOfItems
as 4.
Note: naming a cell array cell
is bad practice because cell()
is a built-in Matlab function. If you name a variable or a function with built-in Matlab functions names, you won't be able to use such built-in function in your script.
Update: as @Daniel correctly pointed out, such solution might not be robust in case a vector contains the element we're looking for twice (or more). If there's a case in which, let's say, one of the arrays in cell
is [1 2 1]
we might want to take into account the fact that 1 appears twice in this array. So let's say we set cell{2,5}=[1 2 1]
, by replacing result
definition as
result=cellfun(@(x)sum(ismember(x,1)),cell)
now result
has the form
1 0 0 0 0
1 0 0 0 2
1 0 0 0 1
and as you can see, now in result(2,5)
there is 2, not 1. Using the very same trick as before (i.e. sum all entries in result
) it's possible to count the number of occurrences of a given element.
Upvotes: 0
Reputation: 36710
For your problem, it is irrelevant where the elements are located in your cell, start flattening the data structure to a simple vector:
v=[mycell{:}];
To count the elements, using histcounts
is a good choice
[x,c]=histcounts(v,min(v):max(v));
A more generic solution which does not rely on v
containing integers is:
[x,c]=histcounts(v,unique(v));
In both cases x returns how often the corresponding value in v was found.
In case your MATLAB version does not know the histcounts
function, replace it with hist
Upvotes: 2