首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Matlab中使用累加数组求和数据

在Matlab中使用累加数组求和数据
EN

Stack Overflow用户
提问于 2014-07-20 05:40:03
回答 1查看 453关注 0票数 3

我有这样的矩阵:

代码语言:javascript
运行
复制
>>D=[1,0,10;3,1,12;3,1,12.5;6,1,6;6,2,11.1;]
D =

1.0000         0   10.0000
3.0000    1.0000   12.0000
3.0000    1.0000   12.5000
6.0000    1.0000    6.0000
6.0000    2.0000   11.1000

我想得到数据的第二列之和,如果它们的第一列是相同的。例如,我想拥有:

代码语言:javascript
运行
复制
E=
1.0000         0
3.0000    2.0000
6.0000    3.0000

所以我试着

代码语言:javascript
运行
复制
b = accumarray(D(:,1),D(:,2),[],[],[],true);
[i,~,v] = find(b);
E = [i,v]

但没起作用。我该怎么办?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-20 05:51:27

uniqueaccumarray结合起来-

代码语言:javascript
运行
复制
[unique_ids,~,idmatch_indx] = unique(D(:,1)); 
%// unique_ids would have the unique numbers from first column and only 
%// used to get the first column of final output, E. 
%// idmatch_indx are tags put on each element corresponding to each unique_ids
%// based on the uniqueness

%// Accumulate and perform summation of elements from second column of D using
%// subscripts from idmatch_indx
E = [unique_ids accumarray(idmatch_indx,D(:,2))]

对于accumarray,通常需要输入您想要在累加元素上使用的函数,但是@sum是默认的函数句柄,在这种情况下可以忽略它。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24847727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档