Consolidating counts & sum by Year Range

1 visualizzazione (ultimi 30 giorni)
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.

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 15 Gen 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))'];

Più risposte (2)

Jakob B. Nielsen
Jakob B. Nielsen il 15 Gen 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?

ME
ME il 15 Gen 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

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by