How to use accumaray to aggregate text/string based?

5 次查看(过去 30 天)
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
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

类别

Help CenterFile Exchange 中查找有关 Oceanography and Hydrology 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by