Computing terms of a sequence generated by a nonlinear difference equation

I would like to compute the first 19 terms of a sequence. I find it takes a very long time. Is there something I am missing? Anyway to speed it up?
It takes 78 secs. Using Excel would be instantaneous.
tic
syms alpha
T=19;
X = sym(1:T);
X(1)=0.1;
for i=2:T
X(i)=(1-alpha - X(i-1)).*X(i-1);
end
disp(X)
toc

 採用された回答

Alan Stevens
Alan Stevens 2020 年 10 月 13 日
Must be the fact that you are using symbolic maths. Without that it's fast (as long as you specify a value for alpha of course):
tic
T=19;
alpha = 0.1;
X = zeros(1,T);
X(1) = 0.1;
for i = 2:T
X(i) = (1-alpha-X(i-1)).*X(i-1);
end
disp(X);
toc

3 件のコメント

Hassan Benchekroun
Hassan Benchekroun 2020 年 10 月 13 日
Thanks Alan but I need to keep vector X as a function of alpha. I use them to maximize a function of X wrt alpha.
The maximization step also takes a very long time, after checking I found that just computing X is time consuming. So I want to try and fix that before dealing with the maximization part.
Thanks again.
Alan Stevens
Alan Stevens 2020 年 10 月 13 日
You could still just make X a function of alpha along the following lines:
tic
T = 19;
% Example calculating X rapidly for many values of alpha.
alpha = 0.01:0.01:1;
X = zeros(numel(alpha),T);
for k = 1:numel(alpha)
X(k,:) = fn(alpha(k),T);
end
toc
function x = fn(alpha,T)
x=zeros(1,T);
x(1) = 0.1;
for i = 2:T
x(i)=(1-alpha-x(i-1))*x(i-1);
end
end
The above calculates 100 sets of 19 values of X in about 0.002 seconds on my laptop.
Hassan Benchekroun
Hassan Benchekroun 2020 年 10 月 13 日
Thanks a lot Alan. Indeed it's quite fast. I will use this for the purpose of my example.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by