MATLAB Answers

Info

This question is closed.

0

I would like to evaluate a partial sum for N=3,N=10,N=25 and at the same (or any N). How can this be done?

Asked by Corey Katz on 5 Feb 2018
Latest activity Closed by John D'Errico
on 6 Feb 2018

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.

  0 Comments

Sign in to comment.

1 Answer

Answer by John D'Errico
on 5 Feb 2018
Edited by John D'Errico
on 5 Feb 2018

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.

  0 Comments

Sign in to comment.


Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today