필터 지우기
필터 지우기

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 CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by