I have an array of say 5 elements and I want to run a loop and find the cumulative sum till the ith iteration eg.
array if f=[1 2 3 4 5]
so in the first iteration sum should be 1,in the 2nd it should be 3,in the third it should be 6 and so on...
what is the most efficient way to do this?
thanks in advance:]

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2015년 6월 22일
편집: Azzi Abdelmalek 2015년 6월 22일

0 개 추천

f=[1 2 3 4 5];
out=cumsum(f)

댓글 수: 4

Terry McGinnis
Terry McGinnis 2015년 6월 22일
this gives the sum of all the elements.I want it till the ith element when the loop is in the ith iteration..
Azzi Abdelmalek
Azzi Abdelmalek 2015년 6월 22일
편집: Azzi Abdelmalek 2015년 6월 22일
k=3
out=sum(f(1:k))
%or you can make a for loop
s(1)=f(1);
for k=2:numel(f)
s(k)=s(k-1)+f(k);
end
or just iterate over the cumsum
f = [1 2 3 4 5]
for s = cumsum(f)
%do something with s
end
Terry McGinnis
Terry McGinnis 2015년 6월 22일
this is what i needed.thanks

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File 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