Cell array summation when arrays are different sizes
Show older comments
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]
Accepted Answer
More Answers (2)
Bruno Luong
on 26 Aug 2020
Edited: Bruno Luong
on 26 Aug 2020
I do just one, let you adapt to the second.
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]};
s1 = cellfun('size',cellname,1)
n = max(s1);
Ap = cellfun(@(a) [a;zeros(n-size(a,1),size(a,2))], cellname, 'unif', 0);
output1 = sum(cell2mat(Ap),2)
output1b = sum(cat(3,Ap{:}),3) % NOTE output1 is sum(output1b,2)
KALYAN ACHARJYA
on 26 Aug 2020
"I am trying to some cell arrays containing matrices of different sizes stored at designated index points to arrays. See the below desired outputs"
Option 1: If you are looking for sum of all array elments within the cell array
data=cell2mat(result(cell_array));
result=sum(data(:))
Option 2: If you are looking for sum of invividial elments (single matrix) within the cell array
result=zeros(1,length(cell_array))
for i=1:length(cell_array)
temp=cell_array{i};
result(i)=sum(temp(:));
end
result
You may avoid the loop also here
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!