Unique entries and operations among columns

1 回表示 (過去 30 日間)
Afonso Cavaco
Afonso Cavaco 2017 年 3 月 1 日
回答済み: Josh 2017 年 3 月 2 日
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.

回答 (1 件)

Josh
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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by