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

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

Réponses (2)

Jos (10584)
Jos (10584) le 17 Mai 2019

1 vote

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

6 commentaires

James Tursa
James Tursa le 17 Mai 2019
Modifié(e) : James Tursa le 17 Mai 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) le 18 Mai 2019
So true, James :-D
Walter Roberson
Walter Roberson le 11 Déc 2023
Modifié(e) : Walter Roberson le 11 Déc 2023
n = 120345428372;
sym(n) * (sym(n)+1) / 2
ans = 
7241511065080263999378
syms m
symsum(m, 1, n)
ans = 
7241511065080263999378
Alexander
Alexander le 11 Déc 2023
Maybe a stupid question, but what is the right answer? 7241511065080263999378 or 7241511065080263868416?
v = sym('7241511065080263999378')
v = 
7241511065080263999378
fprintf('%.999g\n', double(v))
7241511065080263868416
So 7241511065080263868416 is the closest double precision representation of 7241511065080263999378
eps(double(v))
ans = 1048576
which is large enough adjacent representable double precision numbers in that range are 1048576 apart.
Alexander
Alexander le 12 Déc 2023
Understood. Thank you

Connectez-vous pour commenter.

Stephan
Stephan le 17 Mai 2019
Modifié(e) : Stephan le 17 Mai 2019

0 votes

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

Catégories

En savoir plus sur Mathematics dans Centre d'aide et File Exchange

Commenté :

le 12 Déc 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by