MATLAB Answers

0

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

Asked by Murad Alzahrani on 17 May 2019
Latest activity Commented on by Jos (10584)
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

Answer by Stephan
on 17 May 2019
Edited by Stephan
on 17 May 2019

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

  0 Comments

Sign in to comment.


Answer by Jos (10584)
on 17 May 2019

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

  2 Comments

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
So true, James :-D

Sign in to comment.