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,
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 .
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.
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.
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.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With