for loop with calculations across rows

12 ビュー (過去 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 Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by