سؤال

I want to calculate the number of rows in a Cell array in MATLAB. 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 =     [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.

هل كانت مفيدة؟

المحلول

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

 [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

The simplest way to achieve this would be to get the first dimension of the size.

rowCount = size(x,1)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top