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!