How to create addition loops

2 次查看(过去 30 天)
Alexandra Robles
Alexandra Robles 2015-10-23
编辑: Thorsten 2015-10-27
Hi!
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

回答(2 个)

Nick Hobbs
Nick Hobbs 2015-10-27
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
Thorsten 2015-10-27
编辑:Thorsten 2015-10-27
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))

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by