Store recursive intermediate values
17 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Stephen23
le 8 Sep 2018
"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.
Réponse acceptée
Stephen23
le 7 Sep 2018
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 commentaires
Stephen23
le 10 Sep 2018
Modifié(e) : Stephen23
le 10 Sep 2018
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Polynomials dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!