How to use cumsum on a segment of a large matrix
1 view (last 30 days)
Show older comments
Inga Beyers
on 27 Jul 2015
Commented: Star Strider
on 27 Jul 2015
I have a matrix
pos_ht=[1 5 5; 1 7 16; 1 9.10 6; 1 12 8; 2 5.5 5; 2 7 5; 2 9.7 6; 3 12 8; 3 4.7 5; 3 7 5; 3 9.10 6];
which represents just an tiny example of the whole matrix, for explanation purposes. The first column represents the week number. I want to cumulate column 3 for each week segment and output all values in a single vector. So the resulting vector should look like this
L=[5; 21; 27; 35; 5; 10; 16; 8; 13; 18; 24]
I am so close to the solution, but have problems with combining, or rather depositing the answers in a single vector:
L=size(pos_ht);
gr=L(1,1);
L=zeros(gr,1); %space allocation
for k=1:3
findrange=find(pos_ht(:,1)==k)
anfang=min(finderange) %anfang=beginning
ende=max(finderange) %ende=end
L=cumsum(pos_ht(anfang:ende,3))
end
Right now the for-loop delivers
L =
5.00
21.00
27.00
35.00
L =
5.00
10.00
16.00
L =
8.00
13.00
18.00
24.00
I have tried adding more "linkage" (basically adding index parentheses everywhere L(k) or findrange(k), but that got me nowhere...
I have a feeling this is really simple! :D Any help will be much appreciated
0 Comments
Accepted Answer
Star Strider
on 27 Jul 2015
This seems to do what you want:
pos_ht=[1 5 5; 1 7 16; 1 9.10 6; 1 12 8; 2 5.5 5; 2 7 5; 2 9.7 6; 3 12 8; 3 4.7 5; 3 7 5; 3 9.10 6];
for k1 = 1:max(pos_ht(:,1))
C{k1,:} = cumsum(pos_ht(k1 == pos_ht(:,1),3));
end
L = cell2mat(C);
2 Comments
Star Strider
on 27 Jul 2015
My pleasure!
It’s a cell array becasue it’s easier to store vectors of different lengths in a a cell array. The two-dimensional array reference forces ‘C{k1,:}’ to be a column vector of (Nx1) vectors (with varying N). This makes it easier to concatenate them using cell2mat, creating the vector you want.
More Answers (0)
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!