MATLAB: A function that computes the sum of a geometric series.

geometric series

A FUNCTION that computes the sum of a geometric series 1 + r + r^2 + r^3 + r^4 + … + r^n, for a given r and N. THe input to the function must be 'r' and 'n'
Not sure what I am doing wrong, but I was trying to take baby steps and work it into a function but that didn't execute.
% create a vector with n elements all identical to r
v = r*ones(1,n);
% calculate [r r^2 r^3….r^n]
v = cumprod(v);
% sum and add one
geoSum = 1 + sum(v);

Best Answer

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)
% sum of a geometric series, up to r^n, as
% 1 + r + r^2 + ... + r^n
% Note there will be n+1 terms in the series.
% generate a vector to be then prodded together
v = [1,r*ones(1,n)];
% use cumprod, instead of using exponents
% to compute each term as r^k
p = cumprod(v);
% sum the terms
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