This question is closed and may reopen in the future if edited.

Asked by Corey Katz
on 5 Feb 2018 at 22:17

What I have right now.

X=pi/2; sum = 0 N =[3 10 25]; %I want the sum of the first 3 terms, the sum of the first 10 terms, etc. for n = 1:N sum = sum + (((-1)^n)/n)*sin(n*X) end sum

end

This only seems to sum the first 3 terms. Is there a way to do this at the same time. I can can do this three times separately, but I wanted a more compact way to write this. Any help would be greatly appreciated.

Answer by John D'Errico
on 5 Feb 2018 at 22:31

Edited by John D'Errico
on 5 Feb 2018 at 22:35

Oh, you made a serious effort. Lots of ways to do it of course. (BTW, NEVER use sum as a variable name!!!!!)

Simplest is:

X = pi/2; N = [3 10 25]; n = 1:max(N); seriesterms = (((-1).^n)./n).*sin(n*X) partialsums = cumsum(seriesterms); partialsums = partialsums(N);

So no explicit loop there. Since you used sum, I assume cumsum is equally valid to use. ;-) Anyway, you never said cumsum was disallowed.

There is nothing wrong with use of a loop of course.

Log in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Log in to comment.