Sum the elements in cell array with different element length
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
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
Plus de réponses (0)
Voir également
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!