Cell array summation when arrays are different sizes
이전 댓글 표시
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]
채택된 답변
추가 답변 (2개)
Bruno Luong
2020년 8월 26일
편집: Bruno Luong
2020년 8월 26일
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
2020년 8월 26일
"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
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!