필터 지우기
필터 지우기

Summing different set of arrays.

조회 수: 4 (최근 30일)
Max
Max 2015년 10월 9일
답변: Guillaume 2015년 10월 9일
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

채택된 답변

C.J. Harris
C.J. Harris 2015년 10월 9일
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));

추가 답변 (2개)

Guillaume
Guillaume 2015년 10월 9일
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 2015년 10월 9일
편집: TastyPastry 2015년 10월 9일
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))

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by