Consolidating counts & sum by Year Range
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Muhammad Rahil Rafiq
el 15 de En. de 2020
Respondida: ME
el 15 de En. de 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.
0 comentarios
Respuesta aceptada
Andrei Bobrov
el 15 de En. de 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))'];
0 comentarios
Más respuestas (2)
Jakob B. Nielsen
el 15 de En. de 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 comentarios
ME
el 15 de En. de 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 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!