How to sum the previous values of a loop and add the current loop value.

15 views (last 30 days)
Sorry if this is a bit of a confusing read, i dont know how to properly describe it.
i have a row matrix variable in a for loop that changes value regularly i want the value of the variable for the current loop added to the sum of varible vaules from the previous loops added together. i want this to be kept if the form of a row matrix (so coloum 1 is added to the second loop value for collum 1, colloum 2 added to second loop value for collum 2... etc.) and have been struggeling of how to do this.
i.e.
loop 1 would be
variable = sum of previous values of variable + current value of variable(1)
loop 2
variable = sum of previous values of variable(1) + current value of variable(2)
loop 3
variable = sum of previous values of variable(1,2) + current value of variable(3)
loop 4
variable = sum of previous values of variable(1,2,3) + current value of variable(4)
kind of like doing,
ans+10 on a calculator, but value of 10 changed each time

Answers (1)

Dinesh
Dinesh on 6 Mar 2023
Edited: Dinesh on 6 Mar 2023
Hi Jay.
You can use the concept of cumulative sum to keep track of the sum of previously calculated values in earlier iterations of the loop.
From your question, I understand that there is a row vector which has a different value in each iteration of the for loop. But the way the current value of this array is calculated is not mentioned, so I'll skip that part. I'm calling this changing row matrix variable as "cur".
I'm assuming that "cumulativeSum" is the row vector that stores the cumulative sum of all the previous iterations of the variable "cur".
I'm assuming that the number of columns in this row matrix will remain the same in all the iterations.
To solve your problem,
  1. Initialize "cur" and "cumulativeSum" to be empty arrays.
  2. Begin the for loop and then write code to calculate the current iteration's value of the row vector "cur".
  3. Check if this is the first iteration of the for loop. If yes, then assign "cumulativeSum" to the variable "cur" (because "cumulativeSum" is an empty vector in the first iteration). If not, then assign "cumulativeSum" to the sum of "cumulativeSum" and "cur" ("cumulativeSum" stores the sum of all the earlier iterations of "cur" and to calculate the current value of "cumulativeSum", "cur" is added to it).
cumulativeSum = cumulativeSum + cur; % each column of cumulativeSum is added to its respective column in cur
4. Once the for loop is executed, the the final value is stored in "cumulativeSum".

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!