# How to save variable and use in future code?

4 ビュー (過去 30 日間)
Igor Arkhandeev 2021 年 2 月 7 日
コメント済み: Igor Arkhandeev 2021 年 2 月 7 日
Good afternoon! I have a problem using the factorial function. This function is called more than 1 million times during the entire code. Due to the large number of identical operations, I get a time for all factorial operations of about 60 seconds. I want to speed this up by calculating the factorial from 1 to 100 once and then returning the value from the resulting vector. How can I do this most effectively?

サインインしてコメントする。

### 採用された回答

Walter Roberson 2021 年 2 月 7 日
The following keeps a cache of all values up to the maximum used so far, and extends the cache as needed.
It uses symbolic toolbox in order to be able to return numerically meaningful results beyond factorial(15)
ffactorial(5)
ans =
120
ffactorial()
ans = [ffactorial(10), factorial(10)]
ans = ffactorial()
ans = double(log10(ffactorial(100)))
ans = 157.9700
ffactorial(100)
ans =
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
function f = ffactorial(n)
persistent precalc
if isempty(precalc); precalc = sym(1); end %factorial(0)
if ~exist('n', 'var') || isempty(n)
f = precalc;
else
assert(all(n>=0) && all(n == fix(n)), 'non-negative integers only!')
for idx = length(precalc): max(n); precalc(idx+1) = precalc(idx) * idx; end
f = precalc(n+1); %vectorized lookup!
end
end
##### 1 件のコメント表示非表示 なし
Igor Arkhandeev 2021 年 2 月 7 日
Thank you very much! I was not previously familiar with this feature, it will make my code much better!

サインインしてコメントする。

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!