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

 Accepted Answer

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 Comments

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.
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.
Thanks a lot Alan. Indeed it's quite fast. I will use this for the purpose of my example.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!