cumprod is a great idea. Well done for thinking of it.
You state that your function did not execute. This may be because it does not have a function header. All you have written is a script.
Have you confused n and N? The code you wrote assumes n.
So how did you call it? What error do you get? Show the full text of the error.
You've made a good start in what you did, so some variations that should work:
function S = geosum1(r,n)
S = sum(cumprod([1,r*ones(1,n)]));
function S = geosum2(r,n)
S = sum(cumprod([1,repmat(r,1,n)]));
It can also be done without cumprod.
function S = geosum3(r,n)
S = sum(r.^(0:n));
Of course, you can break it into multiple lines. That makes the code more readable, and MATLAB does not charge extra if you use an extra line. For example:
function S = geosum4(r,n)
v = [1,r*ones(1,n)];
p = cumprod(v);
S = sum(p);
Comments are very important, as they help you to understand what you wrote, when you are forced to debug code written a year ago (or 30 years ago.) As well, too often once finds code written by a colleague, that you need to use. It can be crucial to be able to understand and follow their code if you will then use it and trust it.
Any of the above schemes will work. To verify that fact, we can even do this:
geosum3(sym('r'),3)
ans =
r^3 + r^2 + r + 1
Best Answer