How to use accumaray to aggregate text/string based?

5 ビュー (過去 30 日間)
Bayu Ardiyanto
Bayu Ardiyanto 2018 年 6 月 8 日
コメント済み: Walter Roberson 2018 年 6 月 8 日
Hi!
I know that we can use accumaray for aggregating some value based on key variable, but can we use it to aggregate string as well? My code to aggregate number value:
a=[11;22;22;11;22;11];
b=[10;20;30;10;20;60];
c=['a';'c';'b';'a';'b';'d'];
[i, ~,n]=unique(a,'first'); %find unique
Mode = accumarray(n , b , size(i) , @(x) mode(x)); %find mode based on keys a
This will resulting Mode=[10;20]
For example, I want to use "Mode" for text based variable, i.e. resulting Text=[a,b]
Is it possible to do it? Any help will be appreciated.
Regards!

回答 (1 件)

Razvan Carbunescu
Razvan Carbunescu 2018 年 6 月 8 日
accumarray is for numerics only but if c is going to only be single characters then can probably still use accumarray as chars are treated as numerics for most functions.
>> a=[11;22;22;11;22;11]';
>> b=[10;20;30;10;20;60]';
>> c=['a';'c';'b';'a';'b';'d']';
>> [i, ~,n]=unique(a,'first'); %find unique
>> res = accumarray(n , c ,size(i), @mode)
res =
2×1 char array
'a'
'b'
If you want to do grouping for more general text can look at groupsummary or findgroups / splitapply workflow to use with char vectors or strings.
>> t = table(a,b,c);
>> groupsummary(t,'a','mode',{'b' 'c'})
ans =
2×4 table
a GroupCount mode_b mode_c
__ __________ ______ ______
11 3 10 a
22 3 20 b
  1 件のコメント
Walter Roberson
Walter Roberson 2018 年 6 月 8 日
You could also look at categorical arrays.

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

カテゴリ

Help Center および File ExchangeOceanography and Hydrology についてさらに検索

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by