How to group rows by a column value which is a chararray

1 次查看(过去 30 天)
I have a cell and I want to group the rows based on a value in the nth cell (say cell 5). I have a list of values which the 2nd column can consists of, lets call this sub.
I do this as follows:
B = accumarray(sub, A);
However I get the following error:
Error using accumarray
Cells of first input SUBS must contain real, full, numeric vectors of equal length.
So how do I use accumarray with a vector of chararray's. Or if this isn't possible, how is there an alternative function which will let me do this.
My sample data is
32 'aes3' 5 107 1 4 'i' 's' 'i'
33 'dad2' 7 40 1 4 'o' 'c' 'a'
34 'aes3' 168 40 1 5 'a' 'w' 'a'
35 'aes3' 169 500 1 1 'a' 's' 'a'
36 'asd2' 222 107 0 4 'o' [] 'i'
Here I want to create 3 dimensional matrix B, which would for instance contain:
B(1) =
32 'aes3' 5 107 1 4 'i' 's' 'i'
34 'aes3' 168 40 1 5 'a' 'w' 'a'
35 'aes3' 169 500 1 1 'a' 's' 'a'
B(2) =
33 'dad2' 7 40 1 4 'o' 'c' 'a'
B(3) =
36 'asd2' 222 107 0 4 'o' [] 'i'
etc.
  2 个评论
Image Analyst
Image Analyst 2017-7-16
编辑:Image Analyst 2017-7-16
Give an example of your data. It's possible you might be able to use categorical() and grpstats() to get your sums, or maybe unique() to turn your char array into unique numbers, and the use accumarray. It's easier for us to try things for you if you give us some small sample data.

请先登录,再进行评论。

回答(1 个)

Guillaume
Guillaume 2017-7-16
Most likely,
[uniquevals, ~, subs] = unique(yourcellarray(:, 5), 'stable'); %stable is optional
accumarray(subs, A)
Or in newer versions of matlab:
subs = findgroups(yourcellarray(:, 5));
accumarray(subs, A) %or splitapply(@sum, A, subs)
  2 个评论
Guillaume
Guillaume 2017-7-16
Of course it doesn't work, the default function for accumarray, when none is given as in your question, is sum. You've never said that you want to group each row with the same char value together each in a cell of a cell array. And sum makes no sense on a cell array.
The easiest way to obtain what you want:
group = fingroups(A(:, 2));
B = splitapply(@(rows) {rows}, A, group)
Using the old fashion unique and accumarray:
[~, ~, group] = unique(A(:, 2));
B = accumarray(group, (1:size(A, 1))', [], @(rowidx) {A(rowidx, :)})

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by