for loop with calculations across rows

조회 수: 14 (최근 30일)
William Ambrose
William Ambrose 2019년 2월 15일
답변: William Ambrose 2019년 2월 15일
Hi there,
I have used MATLAB for less than a year and I now think I need to get the FOR loop (no previous experience).
a = [1 2 3 4 5 6; 1.05 1.08 0.98 1.0 1.01 0.93]'
a =
1.0000 1.0500
2.0000 1.0800
3.0000 0.9800
4.0000 1.0000
5.0000 1.0100
6.0000 0.9300
Need a FOR loop in MATLAB to calculate the EOD vector below
excel_view.png
Calculation in Excel
C2 is A1*B1
C3 is C2*B3 + A2*B3
Etc.
I intend to use this on tables with more than 100,000 lines, but will implement on subgroups (assumption is to use splitapply). I think it could be sensible to consider preallocate to a vector with zeros, great if the solution can include preallocation and if you have considerations on how the FOR loop can be integrated into splitapply.
Thank you for your help, kind regards,
William
  댓글 수: 1
William Ambrose
William Ambrose 2019년 2월 15일
Sorry I see that an error has made its way into the description. Should be
Calculation in Excel
C2 is A1*B1
C3 is C2*B3 + A3*B3
Etc.

댓글을 달려면 로그인하십시오.

채택된 답변

William Ambrose
William Ambrose 2019년 2월 15일
Found out :
a = [1 2 3 4 5 6; 1.05 1.08 0.98 1.0 1.01 0.93]' ;
x = zeros(length(a),1) ;
x(1) = a(1,1).* a(1,2) ;
for n = 2:length(a)
x(n) = a(n,1) * a(n,2) + x(n-1)*a(n,2);
end
b = [a,x]
b =
1.0000 1.0500 1.0500
2.0000 1.0800 3.2940
3.0000 0.9800 6.1681
4.0000 1.0000 10.1681
5.0000 1.0100 15.3198
6.0000 0.9300 19.8274
>>

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by