Find the number of non-empty cells in each row of a cell array

33 次查看(过去 30 天)
I have a cell array of tables where each row contains data for one specimen and each column of that row contains results of repeated tests for that specimen. There are different numbers of tests in each row.
I would like to process each row based on the number of tests. How can I determine the number of cells in each row that contain tables? For example, the first row contains 12 cells, the second contains 14, etc.

采纳的回答

Adam Danz
Adam Danz 2022-11-17
编辑:Adam Danz 2022-11-17
Here's a demo that
  1. creates a cell array of tables and empty cells
  2. determines which cells contain a table
  3. counts the number of tables per row
c = cell(3,4);
c([1,2,3,4,6,10,12]) = {array2table(rand(5))}
c = 3×4 cell array
{5×5 table} {5×5 table } {0×0 double} {5×5 table } {5×5 table} {0×0 double} {0×0 double} {0×0 double} {5×5 table} {5×5 table } {0×0 double} {5×5 table }
y = cellfun(@istable, c)
y = 3×4 logical array
1 1 0 1 1 0 0 0 1 1 0 1
nTablesPerRow = sum(y,2)
nTablesPerRow = 3×1
3 1 3
If you'd rather count any cell that is not empty,
y2 = ~cellfun(@isempty, c)
y2 = 3×4 logical array
1 1 0 1 1 0 0 0 1 1 0 1
nNonEmptiesPerRow = sum(y2,2)
nNonEmptiesPerRow = 3×1
3 1 3
  12 个评论
Jim McIntyre
Jim McIntyre 2022-11-29
The ' transform definitely made the difference.
Y is a 7x18 logical, yet ind is a 113x1 double, and data{i} wants a 1x113.
From the help for find:
If X is a multidimensional array, then find returns a column vector of the linear indices of the result.
Thank you again for all your help on this!
Adam Danz
Adam Danz 2022-11-30
Ah, of course. Thanks @Jim McIntyre. That's what I get for running code in my head rather than actually testing it 😊
I'll update my previous comment to avoid confusions for any future visitors.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by