MATLAB: Sum the elements in cell array with different element length

cellsnansum

Hi everyone,
I need to calculate the sum of elements in a cell array per column. I'm assuming that the cell is 4×4 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.

Best Answer

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{:}));