MATLAB: Cell array summation when arrays are different sizes

cell arraysMATLABmatrix manipulation

I am trying to some cell arrays containing matrices of different sizes stored at designated index points to arrays. See the below desired outputs.
% First Cell Input
cellname = {...
[1 1 1; ...
2 2 2; ...
3 3 3], ...
[1 1 1; ...
2 2 2; ...
3 3 3; ...
4 4 4; ...
5 5 5; ...
6 6 6], ...
[1 1 1; ...
2 2 2; ...
3 3 3; ...
4 4 4; ...
5 5 5; ...
6 6 6; ...
7 7 7; ...
8 8 8; ...
9 9 9]};
% Summed rowise to the below matrix
output1 =[9
18
27
16
30
36
21
24
27]
output1b =[3 3 3; ...
6 6 6; ...
9 9 9; ...
8 8 8; ...
10 10 10; ...
12 12 12; ...
7 7 7; ...
8 8 8; ...
9 9 9]
% Second Cell Input
cellname2 = {...
[1 2 3; ...
1 2 3; ...
1 2 3], ...
[1 2 3 4 5 6; ...
1 2 3 4 5 6; ...
1 2 3 4 5 6], ...
[1 2 3 4 5 6 7 8 9; ...
1 2 3 4 5 6 7 8 9; ...
1 2 3 4 5 6 7 8 9]};
% Summed columnwise to the below matrix
output2 = [9 18 27 24 30 36 21 24 27]
output2b = [3 6 9 8 10 12 7 8 9; ...
3 6 9 8 10 12 7 8 9; ...
3 6 9 8 10 12 7 8 9]

Best Answer

Without any padding with extra zeros/NaN/etc.
Generate some indices to use accumarray to sum only the required elements:
>> in1 = {[1,1,1;2,2,2;3,3,3],[1,1,1;2,2,2;3,3,3;4,4,4;5,5,5;6,6,6],[1,1,1;2,2,2;3,3,3;4,4,4;5,5,5;6,6,6;7,7,7;8,8,8;9,9,9]}
in1 =
[3x3 double] [6x3 double] [9x3 double]
>> fun = @(m)ndgrid(1:size(m,1),1:size(m,2));
>> [i1r,i1c] = cellfun(fun,in1,'uni',0);
>> i1r = vertcat(i1r{:});
>> i1c = vertcat(i1c{:});
>> tmp = vertcat(in1{:});
>> z1a = accumarray(i1r(:),tmp(:))
z1a =
9
18
27
24
30
36
21
24
27
>> z1b = accumarray([i1r(:),i1c(:)],tmp(:))
z1b =
3 3 3
6 6 6
9 9 9
8 8 8
10 10 10
12 12 12
7 7 7
8 8 8
9 9 9
And similarly for the other direction:
>> in2 = {[1,2,3;1,2,3;1,2,3],[1,2,3,4,5,6;1,2,3,4,5,6;1,2,3,4,5,6],[1,2,3,4,5,6,7,8,9;1,2,3,4,5,6,7,8,9;1,2,3,4,5,6,7,8,9]}
>> [i2r,i2c] = cellfun(fun,in2,'uni',0);
>> i2r = horzcat(i2r{:});
>> i2c = horzcat(i2c{:});
>> tmp = horzcat(in2{:});
>> z2a = accumarray(i2c(:),tmp(:)).'
z2a =
9 18 27 24 30 36 21 24 27
>> z2b = accumarray([i2r(:),i2c(:)],tmp(:))
z2b =
3 6 9 8 10 12 7 8 9
3 6 9 8 10 12 7 8 9
3 6 9 8 10 12 7 8 9
Probably could be generalized for any arbitrary input arrays and requested dimension (that exercise is left up to the reader).