フィルターのクリア

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 Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by