Unique entries and operations among columns
1 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a 2162402x3 array.
first column is id second column is age third column is value
I need to have an unique id (remove repeated entries) with the value sum for each id, while retaining corresponding age. in the end I should get an 56943x3 array.
what is the easiest way to accomplish this?
kind regards.
0 个评论
回答(1 个)
Josh
2017-3-2
Try using unique on just the ID's part of the array (I'll assume you're input is called "array"):
[ids, ii, jj] = unique(array(:, 1));
This will get you the first column of output. ii stores the index of (I believe) the first occurrence of each corresponding value in ids in array(:, 1). (i.e. ids(1) = array(ii(1),:)). Thus, you can get the ages using:
ages = array(ii, 2);
To get the last column, the sum of the ages, you'll use the third output of unique, jj. For each id in the original array, jj gives its index in the unique ids array. This will give you the sum of the ages:
sums = accumarray(jj, array(:, 3));
There a lot of different ways to use accumarray. When you give it two column vectors (as above) it essentially does this:
for i = 1 : numel(jj)
sums(jj(i)) = sums(jj(i)) + array(i, 3);
end
0 个评论
另请参阅
类别
在 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!