# using function with loop

1 view (last 30 days)
sermet OGUTCU on 26 Apr 2021
Commented: sermet OGUTCU on 27 Apr 2021
function [b, n, index] = RunLength(x)
d = [true; diff(x(:)) ~= 0]; % TRUE if values change
b = x(d); % Elements without repetitions
k = find([d.', true]); % Indices of changes
n = diff(k); % Number of repetitions
index = k(1:numel(k) - 1);
if iscolumn(x)
n = n.';
index = index.';
end
end
data = [1.2;1.0;0.05;0.4;0.3;0.2;0.1;0.05;0.04;0.03;0.03;0.02;0.01;0.001;0.01;0.01;0.001 ] ;
[b, n, index] = RunLength(data < 0.1);
match = find(b & n >= 10, 1);
result = index(match)
% This function find the number of row which 10 consecutive rows from the
% this computed row are smaller than 0.10. The result equals 8th row.
I need to use this function with loop such as;
data= 605x1 array includes numeric data
I need to compute the "result" with every 121 rows within 605 rows. So I need to run RunLength function five times (to produce five different result ) using the every 121 rows of the "data". I tried the below codes but it doesn't work;
i=1:121:605
for j=5
[b(:,j), n(:,j), index(:,j)] = RunLength(abs(data(i(j))) < 0.1);
match(j) = find(b(:,j) & n(:,j) >= 10, 1);
result(j) = index(match)
end

Jan on 26 Apr 2021
Edited: Jan on 26 Apr 2021
Result = zeros(1, 5);
iResult = 0;
for k = 1:121:605
datak = data(k:k+120);
[b, n, index] = RunLength(datak < 0.1);
match = find(b & n >= 10, 1);
iResult = iResult + 1;
Result(iResult) = index(match);
end
Maybe you have to catch the case, that match is empty.
Alternatively:
Result = zeros(1, 5);
iResult = 0;
for k = 1:5
index = (k - 1)*121 + 1;
datak = data(k:k+120);
[b, n, index] = RunLength(datak < 0.1);
match = find(b & n >= 10, 1);
Result(k) = index(match);
end
sermet OGUTCU on 27 Apr 2021
Dear @Jan
Thank you very much for your solution.