for loop with calculations across rows

11 visualizzazioni (ultimi 30 giorni)
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 Commento
William Ambrose
William Ambrose il 15 Feb 2019
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.

Accedi per commentare.

Risposta accettata

William Ambrose
William Ambrose il 15 Feb 2019
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
>>

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by