natashka
natashka

Reputation: 25

My approximate entropy script for MATLAB isn't working

This is my Approximate entropy Calculator in MATLAB. https://en.wikipedia.org/wiki/Approximate_entropy I'm not sure why it isn't working. It's returning a negative value.Can anyone help me with this? R1 being the data.

FindSize = size(R1);

N = FindSize(1);
% N = input ('insert number of data values');
%if you want to put your own N in, take away the % from the line above 
and
%insert the % before the N = FindSize(1)

%m = input ('insert m: integer representing length of data, embedding 
dimension ');
m = 2;
%r = input ('insert r: positive real number for filtering, threshold 
');
r = 0.2*std(R1);

for x1= R1(1:N-m+1,1)
D1 = pdist2(x1,x1);
C11 = (D1 <= r)/(N-m+1);
c1 = C11(1);
end

for i1 = 1:N-m+1
s1 = sum(log(c1));
end

phi1 = (s1/(N-m+1));

for x2= R1(1:N-m+2,1)
D2 = pdist2(x2,x2);
C21 = (D2 <= r)/(N-m+2);
c2 = C21(1);
end

for i2 = 1:N-m+2
s2 = sum(log(c2));
end

phi2 = (s2/(N-m+2));

Ap = phi1 - phi2;
Apen  = Ap(1)

Upvotes: 0

Views: 493

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23685

Following the documentation provided by the Wikipedia article, I developed this small function that calculates the approximate entropy:

function res = approximate_entropy(U,m,r)

    N = numel(U);
    res = zeros(1,2);

    for i = [1 2]
        off = m + i - 1;
        off_N = N - off;
        off_N1 = off_N + 1;

        x = zeros(off_N1,off);

        for j = 1:off
            x(:,j) = U(j:off_N+j);
        end

        C = zeros(off_N1,1);

        for j = 1:off_N1
            dist = abs(x - repmat(x(j,:),off_N1,1));
            C(j) = sum(~any((dist > r),2)) / off_N1;
        end

        res(i) = sum(log(C)) / off_N1;
    end

    res = res(1) - res(2);

end

I first tried to replicate the computation shown the article, and the result I obtain matches the result shown in the example:

U = repmat([85 80 89],1,17);
approximate_entropy(U,2,3)

ans =
      -1.09965411068114e-05

Then I created another example that shows a case in which approximate entropy produces a meaningful result (the entropy of the first sample is always less than the entropy of the second one):

% starting variables...

s1 = repmat([10 20],1,10);
s1_m = mean(s1);
s1_s = std(s1);

s2_m = 0;
s2_s = 0;

% datasample will not always return a perfect M and S match
% so let's repeat this until equality is achieved...

while ((s1_m ~= s2_m) && (s1_s ~= s2_s))
    s2 = datasample([10 20],20,'Replace',true,'Weights',[0.5 0.5]);
    s2_m = mean(s2);
    s2_s = std(s2);
end

m = 2;
r = 3;

ae1 = approximate_entropy(s1,m,r)
ae2 = approximate_entropy(s2,m,r)

ae1 =
      0.00138568170752751
ae2 =
      0.680090884817465

Finally, I tried with your sample data:

fid = fopen('O1.txt','r');
U = cell2mat(textscan(fid,'%f'));
fclose(fid);

m = 2;
r = 0.2 * std(U);
approximate_entropy(U,m,r)

ans =
      1.08567461184858

Upvotes: 3

Related Questions