# Looping Factorial that adds successive terms

5 views (last 30 days)
David Ramirez on 10 Dec 2019
Answered: Rik on 10 Dec 2019
Writing a code that add sucessive terms but the denominator increases in increments of 1!.
So in example
p(x) = yi +ma(1) + a(2) m(m-1)/2!
I am unable to write a for loop that adds sucessive terms. Here is what I have
for m_2=2:n
mprod = mprod*((m+(1-(m_2-1)))/factorial(m_2-1));
yi = yi +a(m_2)*mprod;
end
My code i believe doesnt increase the factorials rather multiples them

Rik on 10 Dec 2019
It is not clear to me what your inputs are and how the calculations should be expanded. Can you give a few examples?
David Ramirez on 10 Dec 2019
I hope this helps this clears up what I was saying. The denominator just multiplies factorials rather than replacing it. I figured the rest out but I cannot get the denominator correct. Rik on 10 Dec 2019
You should have just shown the last line. I first spent quite some time finding the correct method of implementing your non-desired output, instead of jumping immediately on the desired ouput.
%generate/pick some values
m=4;%this code also works for m=1, in which case it will return yi unchanged
a=rand(m+1,1);
yi=0;
%factors for the elements of a:
%m / 1
%m*(m-1) / 1*2
%m*(m-1)*(m-2)/ 1*2*3
numerator=m-( 0:(m-2) );
numerator=cumprod(numerator);
divisor=1:(m-1);
divisor=cumprod(divisor);
mprod=numerator./divisor;
mprod=reshape(mprod,[],1);%make the products the same shape as a(2:m)
%perform actual calculation
yi=yi + sum( a(2:m).*mprod );
The values in mprod seem extremely predictable. You should probably have a look at how to produce it directly, instead of dividing large numbers. At some point you will generate too large values and inaccuracies will creep in that you could avoid. I will leave that as an excersize for you.