You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
Adding loop for a code
2 views (last 30 days)
Show older comments
I'm using the code from the link below
I need your help in modifing the code in the above link. I want to modify the code to add a loop for it. For example I have 2000 obervation and I need it to calcualte entropy for the first 120 obervation. Then it will take the next 120 obervation by leaving the first observation (1-lag). The output will be a vector of sample entropy.
2 Comments
Walter Roberson
on 27 Sep 2020
Then it will take the next 120 obervation by leaving the first observation (1-lag)
I am not sure that I understand that ? Is lag fixed? Is lag something you would calculate by using a function such as https://www.mathworks.com/help/signal/ref/finddelay.html ?
Do I understand correctly that the first iteration, you would submit the first 120 observations (total = 120), calculate entropy, then each iteration after that, you would add in an artificial first sample that had value (1-lag) together with the next 120 observations, for a total of 121 observations going into the entropy calculation?
Hatem Akeel
on 27 Sep 2020
Thanks for your prompt response !
lets say you have the folllowing observatiion ( 10,20,30,40,... 20,000) which are 2000 obsevations. The first iteration or calcuation will be from 10 until 1200. 2nd iteration or calcuation will be from 20 until 1210. 3rd will be from 30 until 1220 and so on and so forth. I need to make this loop of calcuation in the code.
I hope that will explain it.
Accepted Answer
Vimal Rathod
on 30 Sep 2020
Hi,
For making a bunch of iterations on the observation array you could directly loop through each element and call the "SampEn" function inside the loop and store the values in an array.
n = 2000; % number of observations
l = 120; % length of single set
observations = rand(1,n); % Consider this as observations
entropy = zeros(1,(n-l+1)); % initializing the entropy vector
for i = 1:(n-l+1)
% just included temporary values in the function.
entropy(i) = SampEn(observations(i:i+l-1),1,0.2);
end
Hope this helps.
13 Comments
Hatem Akeel
on 30 Sep 2020
Thank you for your reply. I tried the code as follow:
% ----------------------------------------------------------------------- %
% H Y D R A %
% ----------------------------------------------------------------------- %
% Function 'sampen' computes the Sample Entropy of a given signal. %
% %
% Input parameters: %
% - signal: Signal vector with dims. [1xN] %
% - m: Embedding dimension (m < N). %
% - r: Tolerance (percentage applied to the SD). %
% - dist_type: (Optional) Distance type, specified by a string. %
% Default value: 'chebychev' (type help pdist for %
% further information). %
% %
% Output variables: %
% - value: SampEn value. Since SampEn is not defined whenever%
% B = 0, the output value in that case is NaN. %
% ----------------------------------------------------------------------- %
% Versions: %
% - 1.0: (21/09/2018) Original script. %
% - 1.1: (09/11/2018) Upper bound is added. Now, SampEn is %
% not able to return Inf values. %
% ----------------------------------------------------------------------- %
% Script information: %
% - Version: 1.0. %
% - Author: V. Martínez-Cagigal %
% - Date: 21/09/2018 %
% ----------------------------------------------------------------------- %
% References: %
% [1] Richman, J. S., & Moorman, J. R. (2000). Physiological %
% time-series analysis using approximate entropy and sample %
% entropy. American Journal of Physiology-Heart and %
% Circulatory Physiology, 278(6), H2039-H2049. %
% ----------------------------------------------------------------------- %
function value = sampen(signal, m, r, dist_type)
% Error detection and defaults
if nargin < 3, error('Not enough parameters.'); end
if nargin < 4
dist_type = 'chebychev';
fprintf('[WARNING] Using default distance method: chebychev.\n');
end
if ~isvector(signal)
error('The signal parameter must be a vector.');
end
if ~ischar(dist_type)
error('Distance must be a string.');
end
if m > length(signal)
error('Embedding dimension must be smaller than the signal length (m<N).');
end
% Useful parameters
signal = signal(:)';
N = length(signal); % Signal length
sigma = std(signal); % Standard deviation
% Create the matrix of matches
matches = NaN(m+1,N);
for i = 1:1:m+1
matches(i,1:N+1-i) = signal(i:end);
end
matches = matches';
% Check the matches for m
d_m = pdist(matches(:,1:m), dist_type);
if isempty(d_m)
% If B = 0, SampEn is not defined: no regularity detected
% Note: Upper bound is returned
value = Inf;
else
% Check the matches for m+1
d_m1 = pdist(matches(:,1:m+1), dist_type);
% Compute A and B
% Note: logical operations over NaN values are always 0
B = sum(d_m <= r*sigma);
A = sum(d_m1 <= r*sigma);
% Sample entropy value
% Note: norm. comes from [nchoosek(N-m+1,2)/nchoosek(N-m,2)]
value = -log((A/B)*((N-m+1)/(N-m-1)));
end
% If A=0 or B=0, SampEn would return an infinite value. However, the
% lowest non-zero conditional probability that SampEn should
% report is A/B = 2/[(N-m-1)(N-m)]
if isinf(value)
% Note: SampEn has the following limits:
% - Lower bound: 0
% - Upper bound: log(N-m)+log(N-m-1)-log(2)
value = -log(2/((N-m-1)*(N-m)));
end
n = 2000; % number of observations
l=120; % length of single set
observations = rand(1,n); % Consider this as observations
entropy = zeros(1,(n-l+1)); % initializing the entropy vector
for i = 1:(n-l+1)
% just included temporary values in the function.
entropy(i) = SampEn(observations(i:i+l-1),1,0.2);
end
end
I got the following error:
unrecognized function or variable 'l'.
Walter Roberson
on 30 Sep 2020
Which line is that error showing up in? That variable does not appear to be used until after it is defined in
l=120; % length of single set
Walter Roberson
on 30 Sep 2020
I do not get an error there.
However, just after there you have
entropy(i) = SampEn(observations(i:i+l-1),1,0.2);
which is an undefined function that happens to be nearly the same as the name of the current function sampen . On sufficiently old versions of MATLAB, the function names were not case sensitive, and the function would have been invoked recursively -- but those days were long gone by the time the script was written in 2018.
If you convert the SampEn reference to sampen thinking that it is an innocent typing mistake, then you get infinite recursion.
It would make the most sense if the lines starting from n = 2000 were a different file intended to test the function, and that SampEn were sampen
Hatem Akeel
on 1 Oct 2020
Thanks again. Yes if I convert it to sampen it will make an infinite recursion. How can make it running the loop required and save each output in a separate file?
Walter Roberson
on 1 Oct 2020
function test_sampen
n = 2000; % number of observations
l = 120; % length of single set
observations = rand(1,n); % Consider this as observations
entropy = zeros(1,(n-l+1)); % initializing the entropy vector
for i = 1:(n-l+1)
% just included temporary values in the function.
entropy(i) = sampen(observations(i:i+l-1), 1, 0.2, 'chebychev');
end
save('NameOfOutputFile.mat', 'entropy')
end
% ----------------------------------------------------------------------- %
% H Y D R A %
% ----------------------------------------------------------------------- %
% Function 'sampen' computes the Sample Entropy of a given signal. %
% %
% Input parameters: %
% - signal: Signal vector with dims. [1xN] %
% - m: Embedding dimension (m < N). %
% - r: Tolerance (percentage applied to the SD). %
% - dist_type: (Optional) Distance type, specified by a string. %
% Default value: 'chebychev' (type help pdist for %
% further information). %
% %
% Output variables: %
% - value: SampEn value. Since SampEn is not defined whenever%
% B = 0, the output value in that case is NaN. %
% ----------------------------------------------------------------------- %
% Versions: %
% - 1.0: (21/09/2018) Original script. %
% - 1.1: (09/11/2018) Upper bound is added. Now, SampEn is %
% not able to return Inf values. %
% ----------------------------------------------------------------------- %
% Script information: %
% - Version: 1.0. %
% - Author: V. Martínez-Cagigal %
% - Date: 21/09/2018 %
% ----------------------------------------------------------------------- %
% References: %
% [1] Richman, J. S., & Moorman, J. R. (2000). Physiological %
% time-series analysis using approximate entropy and sample %
% entropy. American Journal of Physiology-Heart and %
% Circulatory Physiology, 278(6), H2039-H2049. %
% ----------------------------------------------------------------------- %
function value = sampen(signal, m, r, dist_type)
% Error detection and defaults
if nargin < 3, error('Not enough parameters.'); end
if nargin < 4
dist_type = 'chebychev';
fprintf('[WARNING] Using default distance method: chebychev.\n');
end
if ~isvector(signal)
error('The signal parameter must be a vector.');
end
if ~ischar(dist_type)
error('Distance must be a string.');
end
if m > length(signal)
error('Embedding dimension must be smaller than the signal length (m<N).');
end
% Useful parameters
signal = signal(:)';
N = length(signal); % Signal length
sigma = std(signal); % Standard deviation
% Create the matrix of matches
matches = NaN(m+1,N);
for i = 1:1:m+1
matches(i,1:N+1-i) = signal(i:end);
end
matches = matches';
% Check the matches for m
d_m = pdist(matches(:,1:m), dist_type);
if isempty(d_m)
% If B = 0, SampEn is not defined: no regularity detected
% Note: Upper bound is returned
value = Inf;
else
% Check the matches for m+1
d_m1 = pdist(matches(:,1:m+1), dist_type);
% Compute A and B
% Note: logical operations over NaN values are always 0
B = sum(d_m <= r*sigma);
A = sum(d_m1 <= r*sigma);
% Sample entropy value
% Note: norm. comes from [nchoosek(N-m+1,2)/nchoosek(N-m,2)]
value = -log((A/B)*((N-m+1)/(N-m-1)));
end
% If A=0 or B=0, SampEn would return an infinite value. However, the
% lowest non-zero conditional probability that SampEn should
% report is A/B = 2/[(N-m-1)(N-m)]
if isinf(value)
% Note: SampEn has the following limits:
% - Lower bound: 0
% - Upper bound: log(N-m)+log(N-m-1)-log(2)
value = -log(2/((N-m-1)*(N-m)));
end
end
Hatem Akeel
on 1 Oct 2020
I really appreciate your help. My code right now is as below and it is just for 448 variables not 2000. I have m =2 and r =0.2. I need to incorporate memory mapping or memmapfile so that it will not crash and save the file in the end. How can I do that?
% ----------------------------------------------------------------------- %
% H Y D R A %
% ----------------------------------------------------------------------- %
% Function 'sampen' computes the Sample Entropy of a given signal. %
% %
% Input parameters: %
% - signal: Signal vector with dims. [1xN] %
% - m: Embedding dimension (m < N). %
% - r: Tolerance (percentage applied to the SD). %
% - dist_type: (Optional) Distance type, specified by a string. %
% Default value: 'chebychev' (type help pdist for %
% further information). %
% %
% Output variables: %
% - value: SampEn value. Since SampEn is not defined whenever%
% B = 0, the output value in that case is NaN. %
% ----------------------------------------------------------------------- %
% Versions: %
% - 1.0: (21/09/2018) Original script. %
% - 1.1: (09/11/2018) Upper bound is added. Now, SampEn is %
% not able to return Inf values. %
% ----------------------------------------------------------------------- %
% Script information: %
% - Version: 1.0. %
% - Author: V. MartÃnez-Cagigal %
% - Date: 21/09/2018 %
% ----------------------------------------------------------------------- %
% References: %
% [1] Richman, J. S., & Moorman, J. R. (2000). Physiological %
% time-series analysis using approximate entropy and sample %
% entropy. American Journal of Physiology-Heart and %
% Circulatory Physiology, 278(6), H2039-H2049. %
% ----------------------------------------------------------------------- %
function value = sampen(signal, m, r, dist_type)
% Error detection and defaults
if nargin < 3, error('Not enough parameters.'); end
if nargin < 4
dist_type = 'chebychev';
fprintf('[WARNING] Using default distance method: chebychev.\n');
end
if ~isvector(signal)
error('The signal parameter must be a vector.');
end
if ~ischar(dist_type)
error('Distance must be a string.');
end
if m > length(signal)
error('Embedding dimension must be smaller than the signal length (m<N).');
end
% Useful parameters
signal = signal(:)';
N = length(signal); % Signal length
sigma = std(signal); % Standard deviation
% Create the matrix of matches
matches = NaN(m+1,N);
for i = 1:1:m+1
matches(i,1:N+1-i) = signal(i:end);
end
matches = matches';
% Check the matches for m
d_m = pdist(matches(:,1:m), dist_type);
if isempty(d_m)
% If B = 0, SampEn is not defined: no regularity detected
% Note: Upper bound is returned
value = Inf;
else
% Check the matches for m+1
d_m1 = pdist(matches(:,1:m+1), dist_type);
% Compute A and B
% Note: logical operations over NaN values are always 0
B = sum(d_m <= r*sigma);
A = sum(d_m1 <= r*sigma);
% Sample entropy value
% Note: norm. comes from [nchoosek(N-m+1,2)/nchoosek(N-m,2)]
value = -log((A/B)*((N-m+1)/(N-m-1)));
end
% If A=0 or B=0, SampEn would return an infinite value. However, the
% lowest non-zero conditional probability that SampEn should
% report is A/B = 2/[(N-m-1)(N-m)]
if isinf(value)
% Note: SampEn has the following limits:
% - Lower bound: 0
% - Upper bound: log(N-m)+log(N-m-1)-log(2)
value = -log(2/((N-m-1)*(N-m)));
end
n = 448; % number of observations
l = 120; % length of single set
observations = rand(1,n); % Consider this as observations
entropy = zeros(1,(n-l+1)); % initializing the entropy vector
for i = 1:(n-l+1)
% just included temporary values in the function.
entropy(i) = sampen(observations(i:i+l-1),1,0.2);
save('NameOfOutputFile.mat', 'entropy')
end
end
Walter Roberson
on 2 Oct 2020
What you want to do is not possible. You have infinite recursion, so you will never finish.
Can. Not. Be. Done.
On the other hand, the code I posted above https://www.mathworks.com/matlabcentral/answers/600511-adding-loop-for-a-code#comment_1032784 does not have infinite recursion and should run quickly.
Hatem Akeel
on 2 Oct 2020
Edited: Hatem Akeel
on 2 Oct 2020
I got the following error
Error: File: sampen.m Line: 46 Column: 1
Function 'sampen' has already been declared within this scope.
function test_sampen
n = 448; % number of observations
l = 120; % length of single set
observations = rand(1,n); % Consider this as observations
entropy = zeros(1,(n-l+1)); % initializing the entropy vector
for i = 1:(n-l+1)
% just included temporary values in the function.
entropy(i) = sampen(observations(i:i+l-1), 1, 0.2, 'chebychev');
end
save('NameOfOutputFile.mat', 'entropy')
end
% ----------------------------------------------------------------------- %
% H Y D R A %
% ----------------------------------------------------------------------- %
% Function 'sampen' computes the Sample Entropy of a given signal. %
% %
% Input parameters: %
% - signal: Signal vector with dims. [1xN] %
% - m: Embedding dimension (m < N). %
% - r: Tolerance (percentage applied to the SD). %
% - dist_type: (Optional) Distance type, specified by a string. %
% Default value: 'chebychev' (type help pdist for %
% further information). %
% %
% Output variables: %
% - value: SampEn value. Since SampEn is not defined whenever%
% B = 0, the output value in that case is NaN. %
% ----------------------------------------------------------------------- %
% Versions: %
% - 1.0: (21/09/2018) Original script. %
% - 1.1: (09/11/2018) Upper bound is added. Now, SampEn is %
% not able to return Inf values. %
% ----------------------------------------------------------------------- %
% Script information: %
% - Version: 1.0. %
% - Author: V. Martínez-Cagigal %
% - Date: 21/09/2018 %
% ----------------------------------------------------------------------- %
% References: %
% [1] Richman, J. S., & Moorman, J. R. (2000). Physiological %
% time-series analysis using approximate entropy and sample %
% entropy. American Journal of Physiology-Heart and %
% Circulatory Physiology, 278(6), H2039-H2049. %
% ----------------------------------------------------------------------- %
function value = sampen(signal, m, r, dist_type)
% Error detection and defaults
if nargin < 3, error('Not enough parameters.'); end
if nargin < 4
dist_type = 'chebychev';
fprintf('[WARNING] Using default distance method: chebychev.\n');
end
if ~isvector(signal)
error('The signal parameter must be a vector.');
end
if ~ischar(dist_type)
error('Distance must be a string.');
end
if m > length(signal)
error('Embedding dimension must be smaller than the signal length (m<N).');
end
% Useful parameters
signal = signal(:)';
N = length(signal); % Signal length
sigma = std(signal); % Standard deviation
% Create the matrix of matches
matches = NaN(m+1,N);
for i = 1:1:m+1
matches(i,1:N+1-i) = signal(i:end);
end
matches = matches';
% Check the matches for m
d_m = pdist(matches(:,1:m), dist_type);
if isempty(d_m)
% If B = 0, SampEn is not defined: no regularity detected
% Note: Upper bound is returned
value = Inf;
else
% Check the matches for m+1
d_m1 = pdist(matches(:,1:m+1), dist_type);
% Compute A and B
% Note: logical operations over NaN values are always 0
B = sum(d_m <= r*sigma);
A = sum(d_m1 <= r*sigma);
% Sample entropy value
% Note: norm. comes from [nchoosek(N-m+1,2)/nchoosek(N-m,2)]
value = -log((A/B)*((N-m+1)/(N-m-1)));
end
% If A=0 or B=0, SampEn would return an infinite value. However, the
% lowest non-zero conditional probability that SampEn should
% report is A/B = 2/[(N-m-1)(N-m)]
if isinf(value)
% Note: SampEn has the following limits:
% - Lower bound: 0
% - Upper bound: log(N-m)+log(N-m-1)-log(2)
value = -log(2/((N-m-1)*(N-m)));
end
end
Walter Roberson
on 2 Oct 2020
Save the following code to file test_sampen.m
function test_sampen
n = 448; % number of observations
l = 120; % length of single set
observations = rand(1,n); % Consider this as observations
entropy = zeros(1,(n-l+1)); % initializing the entropy vector
for i = 1:(n-l+1)
% just included temporary values in the function.
entropy(i) = sampen(observations(i:i+l-1), 1, 0.2, 'chebychev');
end
save('NameOfOutputFile.mat', 'entropy')
end
Walter Roberson
on 2 Oct 2020
Save the following code to sampen.m
% ----------------------------------------------------------------------- %
% H Y D R A %
% ----------------------------------------------------------------------- %
% Function 'sampen' computes the Sample Entropy of a given signal. %
% %
% Input parameters: %
% - signal: Signal vector with dims. [1xN] %
% - m: Embedding dimension (m < N). %
% - r: Tolerance (percentage applied to the SD). %
% - dist_type: (Optional) Distance type, specified by a string. %
% Default value: 'chebychev' (type help pdist for %
% further information). %
% %
% Output variables: %
% - value: SampEn value. Since SampEn is not defined whenever%
% B = 0, the output value in that case is NaN. %
% ----------------------------------------------------------------------- %
% Versions: %
% - 1.0: (21/09/2018) Original script. %
% - 1.1: (09/11/2018) Upper bound is added. Now, SampEn is %
% not able to return Inf values. %
% ----------------------------------------------------------------------- %
% Script information: %
% - Version: 1.0. %
% - Author: V. Martínez-Cagigal %
% - Date: 21/09/2018 %
% ----------------------------------------------------------------------- %
% References: %
% [1] Richman, J. S., & Moorman, J. R. (2000). Physiological %
% time-series analysis using approximate entropy and sample %
% entropy. American Journal of Physiology-Heart and %
% Circulatory Physiology, 278(6), H2039-H2049. %
% ----------------------------------------------------------------------- %
function value = sampen(signal, m, r, dist_type)
% Error detection and defaults
if nargin < 3, error('Not enough parameters.'); end
if nargin < 4
dist_type = 'chebychev';
fprintf('[WARNING] Using default distance method: chebychev.\n');
end
if ~isvector(signal)
error('The signal parameter must be a vector.');
end
if ~ischar(dist_type)
error('Distance must be a string.');
end
if m > length(signal)
error('Embedding dimension must be smaller than the signal length (m<N).');
end
% Useful parameters
signal = signal(:)';
N = length(signal); % Signal length
sigma = std(signal); % Standard deviation
% Create the matrix of matches
matches = NaN(m+1,N);
for i = 1:1:m+1
matches(i,1:N+1-i) = signal(i:end);
end
matches = matches';
% Check the matches for m
d_m = pdist(matches(:,1:m), dist_type);
if isempty(d_m)
% If B = 0, SampEn is not defined: no regularity detected
% Note: Upper bound is returned
value = Inf;
else
% Check the matches for m+1
d_m1 = pdist(matches(:,1:m+1), dist_type);
% Compute A and B
% Note: logical operations over NaN values are always 0
B = sum(d_m <= r*sigma);
A = sum(d_m1 <= r*sigma);
% Sample entropy value
% Note: norm. comes from [nchoosek(N-m+1,2)/nchoosek(N-m,2)]
value = -log((A/B)*((N-m+1)/(N-m-1)));
end
% If A=0 or B=0, SampEn would return an infinite value. However, the
% lowest non-zero conditional probability that SampEn should
% report is A/B = 2/[(N-m-1)(N-m)]
if isinf(value)
% Note: SampEn has the following limits:
% - Lower bound: 0
% - Upper bound: log(N-m)+log(N-m-1)-log(2)
value = -log(2/((N-m-1)*(N-m)));
end
end
Walter Roberson
on 2 Oct 2020
Now invoke test_sampen
Hatem Akeel
on 5 Oct 2020
Thanks appreciate your help. Works great!
More Answers (0)
See Also
Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)