Effacer les filtres
Effacer les filtres

Sum the elements in cell array with different element length

2 vues (au cours des 30 derniers jours)
Yasmin Tamimi
Yasmin Tamimi le 23 Mar 2016
Commenté : Yasmin Tamimi le 23 Mar 2016
Hi everyone,
I need to calculate the sum of elements in a cell array per column. I'm assuming that the cell is 4x4 and each element in it is a row vector with random length. In order to be able to sum the column I need to check the longest vector and pad all the other cell elements with nans or zeros. Here is what I did:
trial = cell(4,4);
trial{1,1} = [1 1 0 0 1 1 0 0];
trial{1,2} = [2 2 2 0 0 0 2 2 2 0 0 0];
trial{1,3} = [3 3 3 3 0 0 0 0 3 3 3 3 0 0 0 0];
trial{1,4} = [4 4 0 0 4 4 0 0];
trial{2,1} = [9 9 0 0 0 9 9 0 0 0 ];
trial{2,2} = [1 1 0 0 1 1 0 0];
trial{2,3} = [2 2 2 0 0 0 2 2 2 0 0 0];
trial{2,4} = [5 5 5 5 5 5 5 5 5 5];
trial{3,1} = [8 8 8 8 0 0 8 8 8 8];
trial{3,2} = [4 4 4 0 0 0 4 4 4 0 0 0];
trial{3,3} = [4 4 4 0 0 0 4 4 4 0 0 0];
trial{3,4} = [6 6 6 6];
trial{4,1} = [1 1 0 0 1 1 0 0];
trial{4,2} = [2 2 2 0 0 0 2 2 2 0 0 0];
trial{4,3} = [3 3 3 3 0 0 0 0 3 3 3 3 0 0 0 0];
trial{4,4} = [7 7 7 0 0 7 7 7];
for i = 1:4
for j = 1:4
trial = trial{i,j}; % dimension is 1xN
if length(trial{i,j})< 10
pad = nan(1,10-length(trial));
trial = [trial pad];
end
trial{i,j} = trial;
end
end
I'm getting the following error: Cell contents reference from a non-cell array object.
And I want to make the threshold (10 here) dynamic depending on the largest length in the column.
Thanks.

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 23 Mar 2016
Modifié(e) : Andrei Bobrov le 23 Mar 2016
m = cellfun(@numel,trial);
k = num2cell(max(m(:))-m);
out = cellfun(@(x,y)[x(:); nan(y,1)]',trial,k,'un',0);
EDIT
out = sum(cellfun(@sum,trial));
or
m = cellfun(@numel,trial);
k = num2cell(max(m(:))-m);
SUM_out = cellfun(@(x,y)[x(:); zeros(y,1)]',trial,k,'un',0);
out = sum(cat(1,SUM_out{:}));
  2 commentaires
Yasmin Tamimi
Yasmin Tamimi le 23 Mar 2016
Thank you! I just did a slight modification: k = num2cell(max(m(:)) - m); and I padded with zeros instead of nans to be able to sum the values up. So now I have trial{16x16} with each cell element 1x16. When I want to add them up I wrote: Sum_columns = cellfun(@sum ,out); But I ended up having Sum_columns{16x16} with each cell element is the summation of all the vector values for that cell. What I want is that for each column of out I need to do element by element summation and the end result will be 1x16
Yasmin Tamimi
Yasmin Tamimi le 23 Mar 2016
Using it in this form will also add up the value the of cell elements column-wise but for all, I just specified the the number of rows and it worked! out = sum(cat(1,SUM_out{1:4})); Thanks a lot!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by