필터 지우기
필터 지우기

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

조회 수: 5 (최근 30일)
Joel Abrahams
Joel Abrahams 2017년 7월 16일
댓글: Guillaume 2017년 7월 16일
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.
Joel Abrahams
Joel Abrahams 2017년 7월 16일
My mistake, I've included some 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
Joel Abrahams
Joel Abrahams 2017년 7월 16일
Doesn't work, but I'll include some sample data.
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