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

12 views (last 30 days)
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?

Answers (1)

Dave B
Dave B on 31 Oct 2021
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!