Switch to unified view

a b/Supporting Functions/lyapunov.m
1
function lam = lyapunov(x,Fs)
2
% calculate lyapunov coefficient of time series
3
4
%x = sin(1:dt:10)'; % this is 68.83
5
%x = (1:dt:10)';    % this is 0
6
%x = randn(1001,1); % this is ~300
7
%x = squeeze(EEG.data(1,1:1001,1))'; %this is 241.
8
dt = 1/Fs;
9
[ndata nvars]=size(x);
10
steps_forward = 5;
11
N2 = floor(ndata/2);
12
N4 = floor(ndata/4);
13
TOL = 1.0e-6;
14
15
exponent = zeros(N4+1,1);
16
tic
17
for i=N4:N2  % second quartile of data should be sufficiently evolved
18
   
19
   %get all points but this one.
20
   js = setdiff(1:ndata-steps_forward,i);
21
   %find the index of the nearest neighbor
22
   [idx] = knnsearch(x(js,:),x(i,:));
23
   indx = js(idx);
24
   
25
%   tic
26
%    dist = norm(x(i+1,:)-x(i,:));
27
%    indx = i+1;
28
%    for j=i:ndata-5
29
%        if (i ~= j) && norm(x(i,:)-x(j,:))<dist
30
%            dist = norm(x(i,:)-x(j,:));
31
%            indx = j; % closest point!
32
%        end
33
%    end
34
%    toc
35
   expn = 0.0; % estimate local rate of expansion (i.e. largest eigenvalue)
36
   for k=1:steps_forward
37
       if norm(x(i+k,:)-x(indx+k,:))>TOL && norm(x(i,:)-x(indx,:))>TOL
38
           expn = expn + (log(norm(x(i+k,:)-x(indx+k,:)))-log(norm(x(i,:)-x(indx,:))))/k;
39
       end
40
   end
41
   exponent(i-N4+1)=expn/steps_forward;   
42
end
43
toc
44
45
sum=0;  % now, calculate the overal average over N4 data points ...
46
for i=1:N4+1
47
    sum = sum+exponent(i);
48
end
49
50
lam=sum/((N4+1)*dt);  
51
% return the average value
52
% if lam > 0, then system is chaotic