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:

  1. https://reference.wolfram.com/language/tutorial/functionsthatremembervaluestheyhavefound.html
  2. memoized recursive functions. how make them fool-proof?
  3. how improve ( mathematica ) performance when dealing recursive functions?
  4. https://mathematica.stackexchange.com/q/18783 _ functions remember values
  5. https://www.mathworks.com/matlabcentral/answers/163145-saving-values-in-a-recursive-function
  6. java retain information in recursive function
  7. 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

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -