MATLAB is calculating what it calculated properly. The issue is, you told it to calculate the wrong thing. Computers are sooooo picky. :)
You don't tell us what values of r that you used. Or what n was when you ran this code. But if you used a large value for n, then yes, it SHOULD return 1. Or it might return inf. Really? What did you write, and why is that?
In fact, you wrote:
1 + 1⁄r^n + 1⁄r^n + 1⁄r^n + … + 1⁄r^n
Your exponent was fixed, at n.
The exponent in what you wrote was CONSTANT, at n. So if n was large, and abs(r ) was relatively large so that 1/abs(r ) is small, then you would see 1 as a result, because the powers will underflow. Or if r is itself small, then you would just get overflows.
The fix is easy, of course. Change n to i in the expression. That is, the exponent of r needs to be the index variable, not the number n itself.
function sum = mysum(r,n)
sum = 1;
for i = 1:n;
sum = sum + 1/(r^i);
And using the name sum for a variable is a really bad idea, as it will cause bugs in your code sometime, when you actually want to use the FUNCTION named sum.
Always avoid using existing function names as variable names.