How can I write a 'for' loop that sums up all elements of a vector?
조회 수: 2 (최근 30일)
이전 댓글 표시
For instance, I have vector a = 1 2 3 4 5, or simply a=[1:5]. How can I write a 'for' loop that sums up all the elements while showing intermediate results? I want the last result to be 15, as in, 1+2+3+4+5. So far I've only managed to sum up elements like this: 1+2 = 3, 2+3 = 5 and so on. What I want is a 'for' loop that factors in the previous summation and sums it up with the next.
The code I've written so far is:
a= [1:5]
for i=1:5
c=sum(a(i)+a(i+1))
disp(c)
end
댓글 수: 1
VBBV
2024년 7월 17일
@Seif you could also simply sum up all the elements in vector as below
a= 1:5
for i=1:5
c=a(1:i);
disp(['The sum is ',num2str(sum(c))])
end
채택된 답변
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 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!