我对 Matlab 很陌生,但我对其他编程语言有一些经验。我在 Matlab 中有一个从 MySQL 导入的非常大的表。它以元胞数组的形式给出,如下所示:

 date   key     sales    weight  name
 12/11  101     1200     20      blue
 12/11  178     1200     70      purple
 13/11  209     1300     15      purple
 12/11  101     1200     10      blue
 14/11  678     1200     10      yellow
 12/11  340     1500     30      green
 17/11  178     1900     50      purple

我希望输出是这样的:
 key     sales    weight  name
 101     2400     30      blue
 178     3100     120     purple
 209     1300     15      purple
 678     1200     10      yellow
 340     1500     30      green

所以我想合并列“键”中具有相同编号的行。同时,我想对“sales”和“weight”列求和并保留“name”列(每个“key”都有相同的“name”,但每个“name”可以有多个“keys”)

我知道这可以通过 for 循环实现,但是由于我必须以类似但不同的方式操作大量表,因此计算量很大。

我读过类似的问题,这可以使用 accumarray 解决,但是可以使用带有 sub 作为单元数组的 accumarray 来完成吗?那会是什么样子?

最佳答案

这是使用 accumarray 的一种方法,但是考虑新的 table 数据结构而不是单元矩阵可能值得您花时间(我相信您可以轻松转换为它)

T = {  101     1200     20      'blue'
       178     1200     70      'purple'
       209     1300     15      'purple'
       101     1200     10      'blue'
       678     1200     10      'yellow'
       340     1500     30      'green'
       178     1900     50      'purple'};

[u, ind, x] = unique([T{:,1}])

key = T(ind,1)
sales = accumarray(x', [T{:,2}])
weight = accumarray(x', [T{:,3}])
name = T(ind,4)

[key, num2cell(sales), num2cell(weight), name]

关于mysql - Matlab 使用带有单元阵列的 accumarray,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21133765/

10-16 08:02