필터 지우기
필터 지우기

how to sum each element in vector

조회 수: 3 (최근 30일)
Jeah MK
Jeah MK 2022년 1월 28일
답변: DGM 2022년 1월 28일
I have a vector a = 1:1:10;
I want to make a vector by sum each elements; for example, s = [1+0 1+2 3+3 6+4 10+5 ...... ];
I use loop, but it doesn't give me a vector.
a = 1:1:10;
s = 0;
for i=1:length(a)
s = s + a(i);
end
thank you

답변 (1개)

DGM
DGM 2022년 1월 28일
a = 1:1:10;
% you could do it with a loop
s = zeros(1,numel(a));
s(1) = a(1);
for i = 2:numel(a)
s(i) = s(i-1) + a(i);
end
s
s = 1×10
1 3 6 10 15 21 28 36 45 55
% or you could just do
s = cumsum(a)
s = 1×10
1 3 6 10 15 21 28 36 45 55

카테고리

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