# Consolidating counts & sum by Year Range

조회 수: 5(최근 30일)
Muhammad Rahil Rafiq 15 Jan 2020
답변: ME 15 Jan 2020
A=[2001 2002 2001 2003 2003 2003 2004 2004 2004 2004 2004 2007;
1 2 3 4 5 6 7 8 9 12 11 12]
I need to know the sum of toys between 2001-2003, 2002-2004, 2005-2007.

로그인 to comment.

### 채택된 답변

Andrei Bobrov 15 Jan 2020
y = [2001, 2002, 2005
2003, 2004, 2007];
A = [2001 2002 2001 2003 2003 2003 2004 2004 2004 2004 2004 2007;
1 2 3 4 5 6 7 8 9 12 11 12]';
lo = A(:,1) >= y(1,:) & A(:,1) <= y(2,:);
i = lo.*(1:3);
data = A(:,2).*lo;
out = [y;accumarray(i(lo),data(lo))'];

로그인 to comment.

### 추가 답변(2개)

Jakob B. Nielsen 15 Jan 2020
Well, if the 2nd row is your toy counts, something like:
indexes=find((2002 <= A(1,:)) & (A(1,:) <= 2004)); %finds the column indexes which is greater than or equal to 2002, but smaller than or equal to 2004 (ie, the 2002-2004 range)
sum(A(2,indexes)); %gives you the sum of the 2nd row entries from the columns that satisfy the above conditions only.
Is this along the likes of what you need?

#### 댓글 수: 0

로그인 to comment.

ME 15 Jan 2020
If you wanted to get an array containing the sums for all of your defined ranges then you could begin with
R = [2001 2003;
2002 2004;
2005 2007];
where each row contains the year to sum from and year to sum until. Then you can use the below to get an array with one sum for each of the ranges defined in R.
[rows,~]=size(R);
for i=1:rows
ii = A(1,:) >= R(i,1) & A(1,:) <= R(i,2);
ii = find(ii == 1);
RangeSum(i) = sum(A(2,ii));
end

#### 댓글 수: 0

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.

Translated by