Matlab使用cell数组和accumarray函数

3

我是一个刚接触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

我想要将在“key”列中具有相同数字的行合并。同时,我想要对“sales”和“weight”列求和,并保留“name”列(每个“key”具有相同的“name”,但每个“name”可以有多个“keys”)。
我知道可以使用for循环实现,但由于我需要以类似但不同的方式操作许多表格,因此这会导致计算量过大。
我已经阅读了类似问题的解决方案,可以使用accumarray来解决,但是能否使用带有cell数组的子函数来完成?它应该是什么样子的?

1
你能提供一下你的cell数组是如何存储的例子吗?它有标题吗?整个“key”列是一个数组,“sales”是一个数组等等? - Stewie Griffin
2个回答

3

这里有一种使用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]

运行得非常好。谢谢你。我会看看Matlab引入的新表格和分类数组! - user3193435

2
x={ '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'};

[~,b,c]=unique([x{:,2}]);
y=[x(b,2),...
    num2cell(sparse(1,c,[x{:,3}]))',...
    num2cell(sparse(1,c,[x{:,4}]))',...
    x(b,[5])];

unique 用于获取重复键的索引。 sparse 用于获取总和。


我觉得你的意思是 y=[x(b,2), num2cell(sparse(1,c,[x{:,3}]))', num2cell(sparse(1,c,[x{:,4}]))', x(b,[5])]?为什么要在 sparse 中求和呢? - Dan
@Dan:你说得对,我只加了销售额,没有加重量。查看sparse([1,1],[1,1],[2,3])以了解如何使用sparse计算总和。 - Daniel
我恐怕还是不太明白。我认为在你的回答中加入一些解释可能会更有价值。 - Dan
如果您将两个值分配给相同的索引,则sparse会使用它们的总和。我认为user3193435应该使用您的答案,accumarray可能更容易理解。 - Daniel
我在我的桌子上测试了它,它工作正常!非常感谢你。 - user3193435

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接