How to create a loop to sum up the elements in a row array one by one?

조회 수: 1 (최근 30일)
chabao
chabao 2021년 10월 31일
답변: Dave B 2021년 10월 31일
Hi all, I have created a row array using below code,
for k = 1:500
c(k)=1/N.*(ecg(k).*exp(-1*i*k*(2*pi/N*t(k))));
end
and I would like to sum up the elements in the row array one by one so that I can have something like this:
a=[ 1 1 1 1 1] %example only
for k=1:5
=> a=[1 2 3 4 5 ] %final answer after the for loop
However, I have no idea what to do next. Can someone help me?

답변 (1개)

Dave B
Dave B 2021년 10월 31일
You can use the cumsum function for this:
a=[1 1 1 1 1];
cumsum(a)
ans = 1×5
1 2 3 4 5
If you have a matrix, and you want to take your sums row-wise, just use the second argument (dim) to specify you want rows:
a=[1 2 3;4 5 6]
a = 2×3
1 2 3 4 5 6
cumsum(a)
ans = 2×3
1 2 3 5 7 9
cumsum(a,2)
ans = 2×3
1 3 6 4 9 15

카테고리

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