Sum the elements in cell array with different element length
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Andrei Bobrov
2016-3-23
编辑:Andrei Bobrov
2016-3-23
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{:}));
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!