Looping Factorial that adds successive terms

조회 수: 1 (최근 30일)
David Ramirez
David Ramirez 2019년 12월 10일
답변: Rik 2019년 12월 10일
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
  댓글 수: 2
Rik
Rik 2019년 12월 10일
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
David Ramirez 2019년 12월 10일
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.
Code.PNG

댓글을 달려면 로그인하십시오.

답변 (1개)

Rik
Rik 2019년 12월 10일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by