MATLAB Answers

### Info

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

## 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

### Corey Katz (view profile)

on 5 Feb 2018 at 22:17
Latest activity Closed by John D'Errico

### John D'Errico (view profile)

on 6 Feb 2018 at 0:07

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

Log in to comment.

## 1 Answer

### John D'Errico (view profile)

Answer by John D'Errico

### John D'Errico (view profile)

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

### John D'Errico (view profile)

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.

#### 0 Comments

Log in to comment.

### Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today