[英]How to calculate the number of rows in a Cell array in MATLAB
I want to calculate the number of rows in a Cell array in MATLAB. 我想在MATLAB中计算Cell数组中的行数。 I use the code below to count the number of columns in a cell array but I do not know its way for counting the rows. 我使用下面的代码来计算单元格数组中的列数,但我不知道它计算行的方式。
filledCells = ~cellfun(@isempty,a);
columns = sum(filledCells,2)
As an example, i've got x as a cell array: 举个例子,我有x作为单元格数组:
x = [5] [1x8 double] [5]
This cell array has one row and three columns. 该单元阵列有一行三列。 I need a code to calculate the number of rows equal to "1" , but I did not find a way to calculate it. 我需要一个代码来计算等于“1”的行数,但我没有找到计算它的方法。
I used most of ideas but it did not work then with the help of what herohuyongtao said i reach to this idea which worked properly 我使用了大部分的想法,但它没有工作,然后在herohuyongtao说我达到这个正确运作的想法的帮助下
[nr,nc]=size(x)
Which nr is the number of rows thanks all of you. 谢谢大家,行数是多少?
A slightly more general approach: works for rows or columns, and takes into account the size of each cell: 稍微更通用的方法:适用于行或列,并考虑每个单元格的大小:
dim = 1; %// 1 for rows, 2 for columns
result = sum(cellfun(@(c) size(c,dim), a), dim);
Example: 例:
>> a = {1, [2 3], []; 4, [], 5}
a =
[1] [1x2 double] []
[4] [] [5]
>> dim = 1;
gives 给
>> result = sum(cellfun(@(c) size(c,dim), a), dim)
result =
2 1 1
Try 尝试
%% "a" is the cell array, total num of rows will be saved in "rows"
num = length(a); % num of objects in "a" - big rows
rows = 0;
for i=1:num
[r c] = size(C{i})
rows = rows+r;
end
实现这一目标的最简单方法是获得大小的第一个维度。
rowCount = size(x,1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.