How to count the amount of cells?

115 ビュー (過去 30 日間)
Hello kity
Hello kity 2012 年 12 月 21 日
編集済み: Jan 2016 年 11 月 29 日
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..

採用された回答

José-Luis
José-Luis 2012 年 12 月 21 日
your_count = cellfun(@(x) numel(x),your_cell_array);
  4 件のコメント
Ni Putu Dewi Nurmalasari
Ni Putu Dewi Nurmalasari 2016 年 11 月 29 日
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 2016 年 11 月 29 日
編集済み: Jan 2016 年 11 月 29 日
@Ni: Please open a new thread for a new question. Then I answer:
len = cellfun('prodofsize', {data.field});
n = histcounts(len, unique(len));

サインインしてコメントする。

その他の回答 (2 件)

Wayne King
Wayne King 2012 年 12 月 21 日
編集済み: Wayne King 2012 年 12 月 21 日
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 2016 年 11 月 29 日
編集済み: Jan 2016 年 11 月 29 日
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.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by