Addition amongst elements in a Cellarray
2 ビュー (過去 30 日間)
古いコメントを表示
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.
0 件のコメント
採用された回答
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 Center および File Exchange で Cell Arrays についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!