Sum of geometric series without loop

Hey! For the function geo(r,varargin) i am trying to find the sum of the following
1 + r + r^2 + r^3 + r^4 + ... + r^n
where n = nargin.
I have searched and lurked at every corner both here and in the "help" in Matlab, but i found no way of "writing"/"setting up" the geometric series without loops, which is what i am trying to accomplish. Finding the sum i can do, but i cannot find a way to write above series without too much effort. Any ideas? What obvious built-in function am i missing?

 Respuesta aceptada

Geoff Hayes
Geoff Hayes el 20 de Jun. de 2014
I'm not all that clear on why you are using n=nargin instead of just passing n into the function as the second input but maybe there is more to your function than just the series.
You can try using cumprod which returns the cumulative product of each element in the input array. For example,
cumprod([1 2 3 4 5])
returns
1 2 6 24 120
where each element (starting from second) is multiplied by the previous element. You can do something similar with r and n as follows
% 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);
Try the above and see what happens!

2 comentarios

Kenan Hoyt
Kenan Hoyt el 20 de Jun. de 2014
It works! Thanks!
Geoff Hayes
Geoff Hayes el 20 de Jun. de 2014
Great!

Iniciar sesión para comentar.

Más respuestas (1)

Roger Stafford
Roger Stafford el 20 de Jun. de 2014
A simpler method:
result = (1-r^(n+1))/(1-r);

2 comentarios

Kenan Hoyt
Kenan Hoyt el 21 de Jun. de 2014
That's really cool. I can't understand how (yet), but it works! Thanks!
It is easy to see why this works. Call the sum s:
s = 1 + r + r^2 + r^3 + r^4 + ... + r^n
Then
s*r = r + r^2 + r^3 + r^4 + r^5 + ... + r^(n+1)
Therefore when you subtract s*r from s, all the terms cancel except the first and last ones:
s - s*r = 1 - r^(n+1)
Hence if you divide both sides by 1-r you get
s = (1-r^(n+1))/(1-r)

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 20 de Jun. de 2014

Comentada:

el 21 de Jun. de 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by