matlab - Are there functions that remember values they have found on Octave? -
are there functions remember values have found on octave?
when make function definition, value of function recomputed every time ask it. in kinds of calculations, may end asking same function value many times. can save time in these cases having language remember function values finds.
for other languages there are, octave not find:
- https://reference.wolfram.com/language/tutorial/functionsthatremembervaluestheyhavefound.html
- memoized recursive functions. how make them fool-proof?
- how improve ( mathematica ) performance when dealing recursive functions?
- https://mathematica.stackexchange.com/q/18783 _ functions remember values
- https://www.mathworks.com/matlabcentral/answers/163145-saving-values-in-a-recursive-function
- java retain information in recursive function
- recursive fibonacci memoization
this optimize recursive functions calls when calculating factorial
or fibonacci
number. why may save , remove exponencial complexity have. since otherwise intermediate computations have carried out several times, resulting in exponential complexity.
as briefly mentioned in matlab link in question, can use persistent variable retain previous calculations.
here's test function using example of calculating factorials:
function f = persistentfactorial(n) % declare variable factorials persistent persistent factorials computed = numel(factorials); if computed == 0 % function called first time; initialize first element factorials(1) = 1; computed = 1; end if n > computed % fill in uncomputed factorials between computed , n % fprintf('calculating factorials between %d , %d\n', computed+1, n); factorials(computed+1:n) = computed+1:n; factorials(computed:n) = cumprod(factorials(computed:n)); end % return requested factorial f = factorials(n); end
if call function fprintf
uncommented, this:
>> persistentfactorial(5) calculating factorials between 2 , 5 % <-- first call function ans = 120 >> persistentfactorial(5) % <-- second call; no new values ans = 120 >> persistentfactorial(6) calculating factorials between 6 , 6 % <-- third call; 1 new value ans = 720
note if want clear persistent variable, can't access directly other function, or command window, can't type clear factorials
. have clear function (or edit it):
clear persistentfactorial
Comments
Post a Comment