How could I sums up 1/n for n=1 to 10000?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a code like this, but I can't run it.
n = 10000; % whatever you want
sum_harm = 0;
for i = 1:n
sum_harm = sum_harm + 1/i;
end
sum_harm
0 commentaires
Réponses (2)
Chunru
le 23 Sep 2022
It can be run as shown below. What problem have you encountered?
n = 10000; % whatever you want
sum_harm = 0;
for i = 1:n
sum_harm = sum_harm + 1/i;
end
sum_harm
3 commentaires
Chunru
le 23 Sep 2022
There is no variables called "result". You should check "sum_harm" after running your code.
To see the intermediate partial sum, simply remove semicolon at the end of sum statement as shown below:
n = 10; % whatever you want
sum_harm = 0;
for i = 1:n
sum_harm = sum_harm + 1/i % ; suppress display; remove it for display
end
sum_harm
Walter Roberson
le 23 Sep 2022
n = 1:10000;
result = cumsum(1./n);
result(end)
plot(n, result)
Image Analyst
le 23 Sep 2022
Why not try it vectorized:
n = 1 : 10000; % whatever you want
sum_harm = sum(1 ./ n)
What problem did you have in running your code? It ran in MATLAB online. Did you type the m-file name into the command window or click the green run triangle on the tool ribbon? Either should work, but what did you do, if anything? Why do you say you can't run it? Why do you not know how to run the code? Try this link if you don't know how to run your MATLAB program:
0 commentaires
Voir également
Catégories
En savoir plus sur Startup and Shutdown dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!