# Find position of the first place a value is reapeted.

1 view (last 30 days)
FV on 24 Apr 2020
Edited: Adam Danz on 4 May 2020
I have a large array larger than this, but I use it as an example. a=[0.9; 1; 0.6; 1.1; 0.2; 0.6; 1.1; 1; 1; 1; 1; 0.5; 0.2].
I want to find the index of the place where a number is reapeted severeal times and after each other.
So I want to find position 8.
0.6 is repeted but not after each other. 1 is the right value but I don't need it to find position 2.
Hope you understand my question. The numbers actually represent a change in number of points from a point cloud

Tommy on 24 Apr 2020
i = find(diff(a)==0,1);

FV on 27 Apr 2020
what if it needs to be repeted three times?
Tommy on 28 Apr 2020
Try this:
i=find([diff(a,2)==0;0]&diff(a)==0,1)
>> a=[0.9; 1; 0.6; 1.1; 0.2; 0.6; 1.1; 1; 1; 1; 1; 0.5; 0.2];
>> i=find([diff(a,2)==0;0]&diff(a)==0,1)
i =
8
>> a=[1; 2; 3; 3; 2; 4; 2; 1; 4; 6; 7; 8; 1; 1; 1; 1; 9];
>> i=find([diff(a,2)==0;0]&diff(a)==0,1)
i =
13

David Hill on 24 Apr 2020
find(diff(a)==0,1);

David Hill on 27 Apr 2020
i=find(diff(a,2)==0,1);%repeated three times
FV on 28 Apr 2020
It dosn't work for me.
FV on 28 Apr 2020
It works for the array I posted but not if I try another one, like this
a=[1; 2; 3; 3; 2; 4; 2; 1; 4; 6; 7; 8; 1; 1; 1; 1; 9];

Adam Danz on 28 Apr 2020
Edited: Adam Danz on 4 May 2020
This problem is not trivial, especially when working with floating decimals that potentially run into round-off error.
Here's a method below that returns the starting index of consecutve numbers with at least nConsec ocurrences in a row.
% Create input vector (row or column)
a = [.9; 0.9; 1; 0.6; 1.1; 0.2; 1.1; 1.1; 1.1; 0.6; 1.1; 1; 1; 1; 1; 0.5; 0.2];
% Minimum number of consecutve values
nConsec = 3;
% Find consecutive numbers. This considers two numbers equal if their difference
% is less than 0.0000001.
% If you want to use exact matches: iseq = abs(a(1:end-1) - a(2:end)) == 0;
iseq = abs(a(1:end-1) - a(2:end)) < 0.0000001;
% Compute the index of the first of each consecutive string.
cLab = cumsum(diff([0;iseq(:)]) == 1) .* iseq(:); %concesutive labels
[counts,bin] = histcounts(cLab,1:max(cLab)+1);
startIdx = arrayfun(@(i)find(cLab==i,1,'first'), bin([counts+1>=nConsec,false]));
result
startIdx =
7 12