How to do a summation with a for loop

Hey all, this is the problem given to me, and this is the code I have written.
(a = 1:5
for a = a
a = a^3 + a^2 + a;
disp(sum(a)) ;
end)
However, it displays
(a =
1 2 3 4 5
3
14
39
84
155)
The code sets a = 155, but I want a = 295, the sum of (3, 14, 39, 84, 155). How would i go about doing so?

Réponses (1)

You are over-writing the variable a -
a = 1:5;
%Initiate a variable as 0 to store the sum
s = 0;
%loop over a, using another variable as the index of for loop
for k = a
%Update sum for every value of a
s = s + (k^3 + k^2 + k);
end
disp(s)
295

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by