Find the sum of cubes of the integers from 1 to 10 using a
for loop.
Answer.
s = 0;
for k = 1:10
s = s + k^3;
end
Explanation: before entering the loop, we initialize the variable
s with 0, meaning that the value of the sum is 0 before we start adding things to it. Each time the command s = s + k^3 is executed, the cube of k is added to s. This repeats for each value in the vector 1:10. When the loop ends, the variable s will contain the sum of cubes.
This example is for illustration only: in practice the array operation
sum((1:10).^3) would be a better choice because it is shorter and possibly more efficient than the loop.
One could use a more descriptive variable name instead of
s, for example total. But do not use sum because this is the name of a built-in Matlab function. Same goes for max and min: since they are names of built-in functions, they should not be used as variable names. Also, although mathematicians often use \(i\) as index variable, it is too easy to confuse with digit \(1\) and so is best avoided.
