How to sum the values of an MxN cell array?

夙愿已清 提交于 2019-12-11 15:11:31

问题


How can I make the sum of values in an MxN cell array? I used cellfun('sum',CellArray{i}) in which, i refers to the MxN index of the CellArray. But because I used it in a loop to count the number of blocks, it gives me error for being out of index.

What's the right way to do that please?


回答1:


I don't know if I got your problem entirely right. You just want the total sum of all elements of a cell array? Assuming they are doubles, you first need to transform your cell array into a matrix, and then you can use the normal sum function.

% example data
xCell = num2cell( magic(10) )

gives you a a 10x10 cell array with some magic numbers from 1 to 100. The following creates a column-vector of all cell contents and sums them up:

S = sum([xCell{:}])

S =

        5050

which is the result good ol' Mr. Gauss didn't need Matlab for.

Alternatively if you're interested in the sum of all single rows or columns, you can use:

S = sum(cell2mat(xCell),dimension)   % dimension = 1 or 2 (or 3)

regarding your comment in your follow-up question, that you actually have complex doubles:

use:

S = sum( real( [xCell{:}] ) )


来源:https://stackoverflow.com/questions/20565290/how-to-sum-the-values-of-an-mxn-cell-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!