필터 지우기
필터 지우기

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

조회 수: 4 (최근 30일)
Amine Ben Ayara
Amine Ben Ayara 2016년 2월 10일
댓글: Amine Ben Ayara 2016년 2월 10일
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