Unique entries and operations among columns

1 visualización (últimos 30 días)
Afonso Cavaco
Afonso Cavaco el 1 de Mzo. de 2017
Respondida: Josh el 2 de Mzo. de 2017
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.

Respuestas (1)

Josh
Josh el 2 de Mzo. de 2017
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

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by