How to group rows by a column value which is a chararray
    4 vues (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
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 commentaires
  Image Analyst
      
      
 le 16 Juil 2017
				
      Modifié(e) : Image Analyst
      
      
 le 16 Juil 2017
  
			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.
Réponses (1)
  Guillaume
      
      
 le 16 Juil 2017
        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 commentaires
  Guillaume
      
      
 le 16 Juil 2017
				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, :)})
Voir également
Catégories
				En savoir plus sur Performance and Memory dans Help Center et File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!