Addition amongst elements in a Cellarray

1 次查看(过去 30 天)
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 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by