How to count the amount of cells?

129 views (last 30 days)
Hello kity
Hello kity on 21 Dec 2012
Edited: Jan on 29 Nov 2016
Hi
I have a cell array, 1x 90. eacht of them has diff set of data,
for example, 1x1 has 10 cells , 1x2 5 cell etcs.
i want to count to count the amount of cells
numel(cellarrayname) gives 90... thats not what i want.
it should count every cell array add cellarray 2 +cell aray 3 etc..

Accepted Answer

José-Luis
José-Luis on 21 Dec 2012
your_count = cellfun(@(x) numel(x),your_cell_array);
  4 Comments
Ni Putu Dewi Nurmalasari
Ni Putu Dewi Nurmalasari on 29 Nov 2016
i have the similar problem. I have data 1x1000 struct with 1 field , row1=1x61 double, row 2=2x50 double, row 3=3x31double, row4=[5,4], row5=[50,55,53]...row 1000=2. I want to make a plot of how many counts for nx61, nx50.....nx2,nx1 in this case if every row is nxm which m value(1....61), i will put 1x61,2x62,3x61..nx61 into 1 group of data. I am hoping to get 61 data in total.thanks
Jan
Jan on 29 Nov 2016
Edited: Jan on 29 Nov 2016
@Ni: Please open a new thread for a new question. Then I answer:
len = cellfun('prodofsize', {data.field});
n = histcounts(len, unique(len));

Sign in to comment.

More Answers (2)

Wayne King
Wayne King on 21 Dec 2012
Edited: Wayne King on 21 Dec 2012
You want to count how many cells are in each element of the cell array?
x = cell(3,1);
x{1} = cell(2,1); x{2} = cell(25,1); x{3} = cell(30,1);
out = cellfun(@numel,x,'uni',0);
numberofelements = sum(cell2mat(out));
In the above, cellfun() gives you cell array with each cell containing the number of elements in each cell of your original cell array.
cell2mat() turns that cell array into a vector, so now you have a vector where each elements gives the number of each elements in the cell arrays of your original cell array.
Finally, I just sum the elements of the vector to get the total number of elements.

Jan
Jan on 29 Nov 2016
Edited: Jan on 29 Nov 2016
cellfun(@numel) is slower than the hard coded
out = cellfun('prodofsize', x);
Unfortuantely this efficient method is hidden in the "Backward compatibility" link. Using the function handle requires a call from Mex to Matlab for each element, while the string method is processed directly inside the C-Mex function. Former versions of Matlab contained the cellfun.c file, which revealed this.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!