如何对MxN单元阵列的值求和? [英] How to sum the values of an MxN cell array?

查看:126
本文介绍了如何对MxN单元阵列的值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在MxN单元格数组中求值之和?我使用了cellfun('sum',CellArray{i}) 其中,i是指CellArrayMxN索引.但是因为我在循环中使用它来计算块数,所以它给我索引不足带来了错误.

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?

推荐答案

我不知道我是否完全解决了您的问题.您只想要一个单元格数组的所有元素的总和?假设它们是双精度数,则首先需要将单元格数组转换为矩阵,然后可以使用常规的sum函数.

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) )

给您一个10x10的单元格数组,其中一些幻数从1到100. 下面创建所有单元格内容的列向量,并将它们加起来:

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

这就是高斯先生不需要Matlab的结果.

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:

使用:

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

这篇关于如何对MxN单元阵列的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆