How to summarize a matrix based on unique groups

I have a vector A=[1 2 1 4; 5 3 5 7; 6 1 8 9], the first row represent age group, and the second row represents skill level, and the third row is the count of people. From A, I want to produce matrix B where is the compact form of A, in other words, if two or more columns represent the people in the same age and skill level group, we remove all of them and only keep one of them. For our example, A([1 2],1) = A([1 2],3) = [1;5], therefore B=[1 2 4; 5 3 7; 14 1 9].

 採用された回答

Star Strider
Star Strider 2018 年 2 月 3 日
編集済み: Star Strider 2018 年 2 月 3 日

2 投票

Try this:
A=[1 2 1 4; 5 3 5 7; 6 1 8 9];
[Au, ~, ic] = unique(A([1 2],:)', 'rows'); % Unique Columns
R3 = accumarray(ic, A(3,:)); % Sum Similar Elements In Row #3
B = [Au R3]' % Desired Result
B =
1 2 4
5 3 7
14 1 9

その他の回答 (1 件)

Kazi
Kazi 2018 年 2 月 3 日

0 投票

Thank you! This is the right answer. But, it is slow. I ran the profiler and it looks like unique function sorts the data and it takes a significant amount of time. Is there any alternative faster solution?

1 件のコメント

Star Strider
Star Strider 2018 年 2 月 3 日
My pleasure!
‘I ran the profiler and it looks like unique function sorts the data and it takes a significant amount of time. Is there any alternative faster solution?’
Not that I am aware of. The unique() function is necessary for the code to work, since it detects the columns with the same values in the first two rows of ‘A’.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

質問済み:

2018 年 2 月 3 日

コメント済み:

2018 年 2 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by