Looping Factorial that adds successive terms
조회 수: 1 (최근 30일)
이전 댓글 표시
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
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?
답변 (1개)
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!