How do I count the number of rows in a cell array's cells?
55 次查看(过去 30 天)
显示 更早的评论
My goal is to create a table as a subset of a cell array's contents. I understand that it's better to preallocate memory size and then truncate empty rows rather than have an array grow with each loop repetition. So I wish to count the total number of rows in each cell as the maximum possible size of the resulting table.
This does not work:
>> size(newvoldata)
ans =
1 200
Nor does this:
>> numel(newvoldata)
ans =
200
For example, one cell can have a table such that
>> height(newvoldata{160})
ans =
439
Is there a MATLAB command that more quickly does the following?
counter = 0;
for loop = 1:length(newvoldata)
counter = counter + size(newvoldata{loop},1);
end
counter
I suspect there is some command similar to numel that does this for cell arrays. Is there one? Or should I use an implicit function ?
1 个评论
采纳的回答
Stephen23
2018-1-17
编辑:Stephen23
2018-1-17
For a cell array of tables:
sum(cellfun(@height,newvoldata))
For a cell array of numeric/char/cell/struct arrays:
sum(cellfun('size',newvoldata,1))
12 个评论
Stephen23
2018-2-15
编辑:Stephen23
2018-2-15
"Just tried both commands and they both failed"
Which "both commands" are you referring to?
Did you use a logical mask like I showed you in a comment nearly one month ago? If you have cells containing a 0x0 numeric then you will need to use a mask, which is why I showed you how to generate and use one.
"The second results in '199', apparently counting the number of non-empty cells"
The second solution I gave in my answer should not count non-empty cells: for a vector cell array it sums the first dimension of all contents of that cell array. To count the non-empty cells you would need something like this:
sum(~cellfun('isempty',newvoldata))
which, depending on the size of the contents of the cell array, may or may not give the same output value. It is possible that the cellfun "backwards compatibility" syntax using 'size' has not been updated to work correctly with tables.
As has been requested before: if you want help then please upload your data in a .mat file.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!