Addition amongst elements in a Cellarray

조회 수: 18 (최근 30일)
Konstantinos Tsitsilonis
Konstantinos Tsitsilonis 2017년 2월 24일
댓글: Konstantinos Tsitsilonis 2017년 2월 24일
Hi all,
I have a 1x6 cell array with each cell being a 2x3 matrix:
C=
[2 x 3] [2 x 3] [2 x 3] [2 x 3] [2 x 3] [2 x 3]
I would like to sum each matrix element with its corresponding element of the same index in the other cells, for all matrix elements and divide each element by the total sum found:
Sum1=C{1}(1,1)+C{2}(1,1)+C{3}(1,1)+....+C{6}(1,1)
Sum2=C{1}(1,2)+C{2}(1,2)+C{3}(1,2)+....+C{6}(1,2)
Sum3=C{1}(1,3)+C{2}(1,3)+C{3}(1,3)+....+C{6}(1,3)
Sum4=C{1}(2,1)+C{2}(2,1)+C{3}(2,1)+....+C{6}(2,1)
.
.
.
Sum6=C{1}(2,3)+...+C{6}(2,3)
And then after finding these sums, divide each individual matrix row by the sums:
Matrix Row 1, col 1 from each cell with Sum1
Matrix Row 1, col 2 from each cell with Sum2
Matrix Row 1, col 3 from each cell with Sum3
Matrix Row 2, col 1 from each cell with Sum4... and so on for each matrix element.
I have managed to do this with a three nested for loops and about 20 lines of code, but I believe that there might be a better way using cellfun which I am unable to think of.
Thanks for your help in advance,
KMT.

채택된 답변

Jan
Jan 2017년 2월 24일
Working with cells is not efficient here. Prefer a numerical array:
D = cat(3, C{:});
S = sum(D, 3);
Result = bsxfun(@ldivide, D, S);
Or in modern Matlab:
Result = D ./ S;
And if you really want to have it as a cell afterwards:
ResultC = num2cell(Result, [1,2]);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by