How to create addition loops
2 views (last 30 days)
Show older comments
Alexandra Robles on 23 Oct 2015
I've been trying to figure out how to do repetitive sums in MATLAB If I have an array of 100 values and want to find the sum between n consecutive digits, how would I write a loop? Each value in the the array is found by adding the values from 1-n. For example, the array reads [1,3,6,10,15,21,28, and so no on] the first value in the array (1) was found by adding 1-1, so 1. The second value in the array is found by adding 1-2, so 1+2=3. The 3rd value found by adding 1-3, so 1+2+3=5. And so on. What I need, is a function that will do the sums to find each value in the array, and add consecutive numbers in the array. So if I called the function tradition(n), it would add up all the values in the array up to n. Example: taddition(4)=1+3+6+10= 20, and 20 would be the output of the function 1 was found by adding 1-1 3 found by adding 1+2=2 6 found by adding 1-3.. 1+2+3=6 10 found by adding 1-4.. 1+2+3+4=10
Nick Hobbs on 27 Oct 2015
I understand you want to implement a function that will find the sum of each value in the array, and add consecutive numbers in the array. This issue sounds similar to implementing a Fibonacci Sequence in MATLAB. The following link will provide you with an example of how to implement a Fibonacci Sequence in MATLAB, which should help you to resolve the issue.
Thorsten on 27 Oct 2015
Edited: Thorsten on 27 Oct 2015
The arrayfun generates the N numbers, and the sum sums over these numbers:
N = 4; % sample value
x = sum(arrayfun(@(x) (sum(1:x)), 1:N))
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!