Store recursive intermediate values
조회 수: 3 (최근 30일)
이전 댓글 표시
I'm trying to save intermediate values when calling recursive function without using global variables. I don't find anything suiting my issue on mathworks topics and I'd need help.
I'm trying to replicate Legendre polynomials. For example I have to compute the 6-th order polynomial, but to compute so I need the first 5-th orders. But I'd like to keep the intermediates polynomails/results instead of only the 6-th polynom.
Here's the funcion I'm using and that I need to adjust:
function Y = Laguerre(X, k)
if (k==0)
Y=1;
elseif (k==1)
Y=1-X;
else
Y=(1/k)*((2*k-1-X).*Laguerre(X,k-1)-(k-1)*Laguerre(X,k-2));
end
end
Any clue could be appreciated !
댓글 수: 4
Stephen23
2018년 9월 8일
"Keep all of the intermediate values"
It is not clear what you mean by this. Which of these do you mean?:
- keep intermediate Y values that occur within the recursive function, that are otherwise discarded when the function returns.
- keep all output values (i.e. the final Y value) from the function, over a range of X.
- some other definition of "intermediate value".... ?
You might know what you want, but we don't. Please explain exactly which values you are talking about, with examples.
채택된 답변
Stephen23
2018년 9월 7일
Method one: nested function: which lets you keep any intermediate values that you want:
function [Yout,C] = Laguerre(Xin, kin)
C = []; to collect any intermediate values
Yout = mynest(Xin,kin)
%
function Y = mynest(X,k)
if (k==0)
Y=1;
elseif (k==1)
Y=1-X;
else
Y=(1/k)*((2*k-1-X).*mynest(X,k-1)-(k-1)*mynest(X,k-2));
end
C(end+1) = .... anything you want
end
end
Method two: a second output argument:
function [Y,C] = Laguerre(Xin, kin)
[Y,C] = mysub(Xin,kin)
end
function [Y,C] = mysub(X,k)
if (k==0)
Y=1;
elseif (k==1)
Y=1-X;
else
[V1,C1] = mysub(X,k-1);
[V2,C2] = mysub(X,k-2);
Y=(1/k)*((2*k-1-X).*V1-(k-1)*V2);
end
C(end+1) = ... something with C1,C2
end
댓글 수: 4
Stephen23
2018년 9월 10일
편집: Stephen23
2018년 9월 10일
Using a nested function:
function C = Laguerre(Xin, kin)
C = nan(1,1+kin);
mynest(Xin,kin);
%
function Y = mynest(X,k)
switch k
case 0
Y = 1;
case 1
Y = 1-X;
otherwise
Y = (1/k)*((2*k-1-X).*mynest(X,k-1)-(k-1)*mynest(X,k-2));
end
C(k+1) = Y;
end
end
And tested:
>> Laguerre(1,3)
ans =
1 0 -0.5 -0.66667
Note that some k values repeat (e.g. k=1 for your example), in which case only the last Y value will be stored for that k value.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Polynomials에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!