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일

0 개 추천

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일

0 개 추천

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))

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2015년 10월 23일

편집:

2015년 10월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by