フィルターのクリア

Sum the elements in cell array with different element length

2 ビュー (過去 30 日間)
Yasmin Tamimi
Yasmin Tamimi 2016 年 3 月 23 日
コメント済み: Yasmin Tamimi 2016 年 3 月 23 日
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.

採用された回答

Andrei Bobrov
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{:}));
  2 件のコメント
Yasmin Tamimi
Yasmin Tamimi 2016 年 3 月 23 日
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 2016 年 3 月 23 日
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!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by