Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I aggregately accumulate a cell array?

Tags:

matlab

Say that I have:

A = {'a.java' 1;'a.java' 2; 'b.java' 1; 'b.java' 0; 'a.java' 4; 'c.java' 6};

I would like to accumulate the second column numbers based on the first column similarity.

I want to get:

B = {'a.java' 1+2+4; 'b.java' 1+0; 'c.java' 6}

How can I achieve that?

Many thanks,

like image 866
Yi. Avatar asked Apr 27 '11 09:04

Yi.


People also ask

How do you accumulate in MATLAB?

B = cumsum( A ) returns the cumulative sum of A starting at the beginning of the first array dimension in A whose size does not equal 1. If A is a vector, then cumsum(A) returns a vector containing the cumulative sum of the elements of A .

How do you create an array in a cell?

When you have data to put into a cell array, create the array using the cell array construction operator, {} . Like all MATLAB® arrays, cell arrays are rectangular, with the same number of cells in each row. myCell is a 2-by-3 cell array. You also can use the {} operator to create an empty 0-by-0 cell array.

How do you initialize a cell array in MATLAB?

Initialize a cell array by calling the cell function, or by assigning to the last element. For example, these statements are equivalent: C = cell(25,50); C{25,50} = []; MATLAB creates the header for a 25-by-50 cell array.

How do you access the elements of a cell array in MATLAB?

There are two ways to refer to the elements of a cell array. Enclose indices in smooth parentheses, () , to refer to sets of cells--for example, to define a subset of the array. Enclose indices in curly braces, {} , to refer to the text, numbers, or other data within individual cells.


2 Answers

You can easily do this without a for loop using the functions UNIQUE and ACCUMARRAY:

>> [uniqueValues,~,index] = unique(A(:,1));
>> B = [uniqueValues num2cell(accumarray(index,[A{:,2}]))]

B = 

    'a.java'    [7]
    'b.java'    [1]
    'c.java'    [6]
like image 86
gnovice Avatar answered Sep 29 '22 13:09

gnovice


Find the unique keys in A (the unique function can conventiently return a mapping from the keys in A to the entry in the unique key set), then iterate over these.

[u,i1,i2]=unique(A(:,1));     % i1 is not needed, actually
Avalues = cell2mat(A(:,2));   % convert numerical part of cell array to matrix
for i=1:max(i2)
    u{i,2}=sum(Avalues(i2==i));
end

This can also be extended to work column-wise on multiple data columns in the cell array.

like image 44
arne.b Avatar answered Sep 29 '22 13:09

arne.b