Summing different set of arrays.

2 views (last 30 days)
Max
Max on 9 Oct 2015
Answered: Guillaume on 9 Oct 2015
7 10 2001 24 10 5 14
7 10 2001 14 15 2 1
7 10 2001 14 13 2 9 =x
31 3 2002 14 9 2 6
1 4 2002 14 19 10 3
1 4 2002 5 30 11 12
I have this table i would like to sum all the values in column 6 corresponding to the value 14 in column 4 for only the year 2002. So 14 appears twice in 2002 column 4 and the corresponding values are 2 and 10 in column 6 and their sum is 12. So i would like my answer to be 12. So far I've written
for x(:,3)==2002
sum(x(x(:,4)==14, 6))
end
What would I need to change around to get the value i wanted of 12. Thank you

Accepted Answer

C.J. Harris
C.J. Harris on 9 Oct 2015
nYear = 2002;
nValue = 14;
x = [7 10 2001 24 10 5 1
7 10 2001 14 15 2 1
7 10 2001 14 13 2 9
31 3 2002 14 9 2 6
1 4 2002 14 19 10 3
1 4 2002 5 30 11 12];
nResult = sum(x((x(:,3) == nYear) & (x(:,4) == nValue),6));

More Answers (2)

Guillaume
Guillaume on 9 Oct 2015
As in all likelyhood your criteria is going to change, I would calculate the sum for each unique combination of year column 4 all at once. This is easily achieved with unique and accumarray:
db = [7 10 2001 24 10 5 1
7 10 2001 14 15 2 1
7 10 2001 14 13 2 9
31 3 2002 14 9 2 6
1 4 2002 14 19 10 3
1 4 2002 5 30 11 12];
keycolumns = [3, 4] %columns used as primary keys
valuecolumn = 6; %column to sum
[keyval, ~, keyindex] = unique(db(:, keycolumns), 'rows')
dbsums = [keyval, accumarray(keyindex, db(:, valuecolumn))]

TastyPastry
TastyPastry on 9 Oct 2015
Edited: TastyPastry on 9 Oct 2015
There's no need to use a for loop for this job. In any case, you've incorrectly set up a for loop. you need a loop control variable and some vector which represents the values the loop control variable takes on as the loop executes. You have a boolean vector.
What I'd do is set up a mask using the && operator with two conditions: x(:,3) == 2002 and x(:,4) == 14. This will find all the values of x where the 3rd column is 2002 and 4th column is 14. Then I'd just use that mask and sum the 6th column using sum. You could do it in one line:
sum(x(x(:,3)==2002&x(:,4)==14,6))

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!