Consolidating counts & sum by Year Range

1 vue (au cours des 30 derniers jours)
Muhammad Rahil Rafiq
Muhammad Rahil Rafiq le 15 Jan 2020
Réponse apportée : ME le 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.

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 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))'];

Plus de réponses (2)

Jakob B. Nielsen
Jakob B. Nielsen le 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?

ME
ME le 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

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by