how to sum different rows within a column

I have 2 columns with 3101 values and i want to add the row 1&2 then row 2&3, 3&4 and so on..
I want to execute this calculation for the entire column with a cummulative sum
p=0.5*(column1(row1+row2))*column2(row2-row1)
the next row should be = 0.5*(column1(row2+row3))*column2(row3-row2) + p
How can I select 2 row values in the same column with the output created in a different column?
Thanks in advance

 Accepted Answer

One approach would be to create the third column independently and then concatenate it at the end —
A = randi(9,10,2);
p = 0;
for k = 1:size(A,1)-1
v(k,:) = (A(k,1)+A(k+1,1))/2 * (A(k+1,2)-A(k,2)) + p;
p = v(k);
end
A(:,3) = [NaN; v]
A = 10×3
8 1 NaN 3 7 33 8 3 11 3 5 22 3 2 13 1 7 23 4 9 28 1 7 23 3 6 21 6 2 3
.

More Answers (1)

"to add the row 1&2 then row 2&3, 3&4 and so on.." you can use conv:
kernel = [1;1];
sums = conv(column1, kernel, 'valid');
kernel = [-1; 1];
diffs = conv(column2, kernel, 'valid');
If you want it multiplied by 0.5 and cumulatively summed, you can .....
Well actually I think Star's for loop approach is much simpler to do and understand than my vectorized approach so just go with that.

Categories

Find more on Get Started with MATLAB 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!