MATLAB Answers

## How writing code sum 1+2+3+4+...+n

Asked by Murad Alzahrani

### Murad Alzahrani (view profile)

on 17 May 2019
Latest activity Commented on by Jos (10584)

### Jos (10584) (view profile)

on 18 May 2019
Hi. How I can writing code in MATLAB sum 1+2+3+4+..+n
and I can change ( n ) to any numbers and MATLAB can sum for me.
Thank you

#### 0 Comments

Sign in to comment.

## 2 Answers

### Stephan (view profile)

Answer by Stephan

### Stephan (view profile)

on 17 May 2019
Edited by Stephan

### Stephan (view profile)

on 17 May 2019

n = 4;
A = sum(1:n)

#### 0 Comments

Sign in to comment.

### Jos (10584) (view profile)

Answer by Jos (10584)

### Jos (10584) (view profile)

on 17 May 2019

or know your math classics ...
n = 120345428372
s = n*(n+1)/2
% sum(1:n) will fail!

James Tursa

### James Tursa (view profile)

on 17 May 2019
Well, n*(n+1)/2 fails also ...
>> n = 120345428372;
>> fprintf("%20f\n",n*(n+1)/2)
7241511065080263868416.000000
>> vpa(n)*vpa(n+1)/2
ans =
7241511065080263999378.0
Jos (10584)

### Jos (10584) (view profile)

on 18 May 2019
So true, James :-D

Sign in to comment.