How can add the rows in n-by-m matrix that have the same indicator in the last column?
1 次查看(过去 30 天)
显示 更早的评论
Hi,
How can add the rows in n-by-m matrix that have the same indicator in the last column?
For example: 10-by-3 matrix, the third column is the indecator:
253638 3309 2
223389 3309 2
255968 3309 2
243943 33309 2
245568 63309 1
242490 93309 3
268464 23309 2
272665 53309 1
241206 83309 1
259310 13309 2
I want to add all rows (all values in first column with the same indicator) with ( all values in second column with the same indicator).
0 个评论
采纳的回答
Jos (10584)
2016-6-6
X = [253638 3309 2
223389 3309 2
255968 3309 2
243943 33309 2
245568 63309 1
242490 93309 3
268464 23309 2
272665 53309 1
241206 83309 1
259310 13309 2]
OUT = cell2mat(arrayfun(@(k) [sum(X(X(:,3)==k,[1 2]),1) k], unique(X(:,3)),'un',0))
2 个评论
Jos (10584)
2016-6-6
Juts modify the function used by arrayfun
OUT = cell2mat(arrayfun(@(k) [sum(X(X(:,3)==k,[1 2]),1) k sum(X(:,3)==k)], unique(X(:,3)),'un',0))
更多回答(2 个)
Azzi Abdelmalek
2016-6-6
编辑:Azzi Abdelmalek
2016-6-6
You can use accumarray function
A=[253638 3309 3
223389 3309 2
255968 3309 2
243943 33309 2
245568 63309 1
242490 93309 3
268464 23309 2
272665 53309 1
241206 83309 1
259310 13309 2]
[ii,~,jj]=unique(A(:,3))
out=accumarray(jj,(1:numel(jj))',[],@(x) {sum(A(x,1:2),1)})
out=[ cell2mat(out) ii]
2 个评论
Walter Roberson
2016-6-6
unique() to find the unique indicators and the number of indicators. Allocate an zero array of appropriate size to hold the results. Loop over the unique indicators finding the rows that match and totaling them and storing that in the results array.
accumarray() is not suitable for your purposes because accumarray cannot operator on row vectors of values.
4 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!