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

 채택된 답변

Star Strider
Star Strider 2022년 3월 31일
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
.

추가 답변 (1개)

Image Analyst
Image Analyst 2022년 3월 31일

0 개 추천

"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.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2022년 3월 31일

답변:

2022년 3월 31일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by