clear all
close all

%%% load data sequence x
load('x.mat')

N = length(x);
R = zeros(N,N);

for in1 = 1:N
    for in2 = 1:N
        R(in1,in2) = (x(in1) == x(in2));
    end
end

%%% Figure: Recurrence plot
figure
ax = axes;
colormap([1 1 1; 0 0 0 ]);
im = imagesc(R*255,'Parent',ax);
set(ax,'YDir','normal');


%%% Length Histogram
l_min = 2;
P = zeros(1,N);

for l = l_min:N
for i = 1:N-l+1
    for j = 1:N-l+1
        %%% Preceding element
        if i ==1 || j ==1
            R_pre = 0;
        else
            R_pre = R(i-1,j-1);
        end
        %%% Following element
        if i == N-l+1 || j == N-l+1
            R_flow = 0;
        else
            R_flow = R(i+l,j+l);
        end 
        %%% Product vector
        prod_vec = zeros(1,l);
        for in = 0:l-1
            prod_vec(in+1) = R(i+in,j+in);
        end
        %%% Histogramm
        P_inc = (1 - R_pre)*(1 - R_flow)*prod(prod_vec);
        P(l) = P(l) + P_inc;   
    end  
end
end

%%%%% Performance measures
l_vec_min_max = [l_min:N];
P_l_min_max = P(l_min:N);
p_l_min_max = P_l_min_max/sum(P_l_min_max);
p_l_min_max = p_l_min_max(p_l_min_max>0);
RP = sum(sum(R)) - N;

%%%%% Performance measures: Recurrence Rate
RR = 100*RP/((N^2) - N)
%%%%% Performance measures: Determinism
DET = 100*(P_l_min_max(1:end-1)*l_vec_min_max(1:end-1)')/RP
%%%%% Performance measures: Entropy
ENTR = -p_l_min_max(1:end-1)*log(p_l_min_max(1:end-1))'

