How Do I find unique values of an element in a matrix

4 次查看(过去 30 天)
I have a matrix that is (110500*4); the First column are identiers/IDs, these values are not unique, meaning same value can appear more than once. I need to find out how many times each ID appears then basically aggregate the matrix based on these unique IDs to where 1st column is: Unique IDs, 2nd, 3rd and 4th : Sum of elements from original table associated with unique ID. Example:
A=[5 12 25 0
2 10 24 0
1 7 25 1
5 5 12 0
2 6 23 1];
then end matrix should have only 3 rows (unique values are 5,2 & 1) with 1st column: unique values, 2nd column : Sum of values associated with unique ID (5) from column 2, and same for the next 2 columns. basically, reduce the matrix to unique ID then aggregate the next columns based on that.

采纳的回答

Stephen23
Stephen23 2016-2-10
编辑:Stephen23 2016-2-10
>> A = [5,12,25,0;2,10,24,0;1,7,25,1;5,5,12,0;2,6,23,1]
A =
5 12 25 0
2 10 24 0
1 7 25 1
5 5 12 0
2 6 23 1
>> [val,~,idx] = unique(A(:,1));
>> out(:,4) = accumarray(idx,A(:,4));
>> out(:,3) = accumarray(idx,A(:,3));
>> out(:,2) = accumarray(idx,A(:,2));
>> out(:,1) = val
out =
1 7 25 1
2 16 47 1
5 17 37 0
  1 个评论
Amine Ben Ayara
Amine Ben Ayara 2016-2-10
THANK YOU IS NOT enough to show my gratitude for your help! LIFE SAVER again!!!!!!! I REALLY appreciate it

请先登录,再进行评论。

更多回答(1 个)

Guillaume
Guillaume 2016-2-10
unique together with accumarray will do exactly what you want:
A=[5 12 25 0; 2 10 24 0; 1 7 25 1; 5 5 12 0; 2 6 23 1];
[values, ~, subs] = unique(A(:, 1));
out = [values, ...
accumarray(subs, A(:, 2)), ...
accumarray(subs, A(:, 3)), ...
accumarray(subs, A(:, 4))]
Another way of doing the last line, with just one call to accumarray:
out = [values, accumarray([repelem(subs, 3), repmat((1:3)', numel(subs), 1)], reshape(A(:, 2:4), [], 1))]

类别

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