How to create a loop with the sum adding up to a given N?
10 views (last 30 days)
The bread-and-butter of any program language is its ability to perform repeated calculations in a “loop”. Variables are often incremented within loops. The statement x = x+ 5; doesn’t make sense mathematically, but it makes perfect sense to Matlab that evaluates the statement to the right of the equals sign first, and then makes the variable on the left equal to this new value. In other words,
x = 0;
x = x+1;
will start off setting x equal to 10, and then will execute a loop 10 times, where each time through it will increment x by 1. When it finishes, x will equal 10.
Modify the following program below so that it returns the sum of the numbers from one to N. Call the program PyramidSum, and test that PyramidSum(10) returns 1+2+3+4+... 55.
Matthew Eicholtz on 5 Oct 2016
This sounds like a homework problem. The answer is basically already in the question.
N = 10;
x = 0;
x = x+ii;
But, for what it's worth, this is not the best way to sum numbers from 1 to N in MATLAB. Try something like:
x = sum(1:N);