How to calculate the sum of values in column 2 if column 1 has a certain value?
Show older comments
I have to analyze stock accounting. I have a large matrix (10000 x 2). In the first column I have the product code and in the second column I have the quantity taken from the storage. Every action has it's own row. How can I calculate the sum for every product?
I don't know how many product codes there are.
I have tried eg. arrayfun and to generate matrices with for loops and then the sum of the splitted matrices, but the results aren't right.
With this code I got the sum separately, but then I got stuck..
n = length(C)-1;
for i = 1:1:n
if C(i,1)~= C(i+1,1)
S = sum(B(i))
end
end
Thank you in advance!
Answers (1)
Andrei Bobrov
on 9 Sep 2013
Edited: Andrei Bobrov
on 9 Sep 2013
a - your array < 10000 x 2 double >
[a1,ii,ii] = unique(a(:,1));
out = [a1,accumarray(ii,a(:,2))];
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!