MATLAB: How do cumulatively add a matrix column based on a vector

cumulatively addmatrix manipulationpatternvector index

Hello all, I have the following matrix,
t =
1.0000 7.0000 0 0
2.0000 9.0000 0.6000 3.0000
3.0000 11.0000 -0.5000 -0.5000
4.0000 13.0000 0.6000 2.4000
5.0000 14.0000 -0.7000 -2.5000
6.0000 18.0000 0.7000 2.4000
7.0000 19.0000 -0.2000 1.0000
8.0000 20.0000 0 1.0000
9.0000 22.0000 0.7000 2.1000
10.0000 23.0000 -0.1000 1.4000
11.0000 24.0000 0 1.4000
12.0000 25.0000 0.2000 0.4000
13.0000 26.0000 0 0.4000
14.0000 28.0000 0.5000 0.5000
15.0000 29.0000 -0.2000 -0.9000
16.0000 30.0000 0.2000 0.5000
17.0000 31.0000 -0.1000 -0.2000
18.0000 32.0000 0.3000 0
19.0000 33.0000 -0.3000 -2.1000
20.0000 34.0000 0.2000 -0.7000
21.0000 35.0000 -0.1000 -1.4000
22.0000 39.0000 0 -1.4000
23.0000 42.0000 -0.3000 -3.5000
24.0000 44.0000 0.3000 -1.4000
25.0000 45.0000 -0.2000 -2.8000
& a vector m, corresponding to column 1 of t, as
m = [1 2 4 9 12 14 18];
So, I need to cumulatively add the values in column 3 of matrix t from
0 (1+1 : 2-1), that is m(1)+1 : m(2)-1
3 (2+1 : 4-1)
5, 6, 7, 8 (4+1 : 9-1)
10, 11 (9+1 : 12-1)
13 (12+1 : 14-1)
15, 16, 17 (14+1 : 18-1)
19 to 25 (18+1 : end)
& put these in column 4. Right now it has incorrect values. The starting points should all be 0. column 3 (m(n)) = 0, meaning m(1) = 0; m(2) = 0, m(4) = 0, etc.
My method with loops produces a lot of overlap & doesn't quite work. Hope this is not too confusing.
Any suggestions? Thanks Damo Nair

Best Answer

Try this:
t = [...
1.0000 7.0000 0 0
2.0000 9.0000 0.6000 3.0000
3.0000 11.0000 -0.5000 -0.5000
4.0000 13.0000 0.6000 2.4000
5.0000 14.0000 -0.7000 -2.5000
6.0000 18.0000 0.7000 2.4000
7.0000 19.0000 -0.2000 1.0000
8.0000 20.0000 0 1.0000
9.0000 22.0000 0.7000 2.1000
10.0000 23.0000 -0.1000 1.4000
11.0000 24.0000 0 1.4000
12.0000 25.0000 0.2000 0.4000
13.0000 26.0000 0 0.4000
14.0000 28.0000 0.5000 0.5000
15.0000 29.0000 -0.2000 -0.9000
16.0000 30.0000 0.2000 0.5000
17.0000 31.0000 -0.1000 -0.2000
18.0000 32.0000 0.3000 0
19.0000 33.0000 -0.3000 -2.1000
20.0000 34.0000 0.2000 -0.7000
21.0000 35.0000 -0.1000 -1.4000
22.0000 39.0000 0 -1.4000
23.0000 42.0000 -0.3000 -3.5000
24.0000 44.0000 0.3000 -1.4000
25.0000 45.0000 -0.2000 -2.8000];
% Extract column 1 of t.
column1 = t(:, 1);
% & a vector m, corresponding to column 1 of t, defined as
m = [1 2 4 9 12 14 18];
for k = 1 : length(m) - 1
index1 = m(k) + 1;
index2 = m(k + 1) - 1;
theSum(k) = sum(column1(index1:index2));
fprintf('Summing column1 from index %d to %d and getting %.1f.\n', index1, index2, theSum(k));
end
You get:
Summing column1 from index 2 to 1 and getting 0.0.
Summing column1 from index 3 to 3 and getting 3.0.
Summing column1 from index 5 to 8 and getting 26.0.
Summing column1 from index 10 to 11 and getting 21.0.
Summing column1 from index 13 to 13 and getting 13.0.
Summing column1 from index 15 to 17 and getting 48.0.