Consolidating counts & sum by Year Range
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Andrei Bobrov
2020-1-15
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 个评论
更多回答(2 个)
Jakob B. Nielsen
2020-1-15
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 个评论
ME
2020-1-15
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!