Info

This question is closed. Reopen it to edit or answer.

Find position of the first place a value is reapeted.

1 view (last 30 days)
FV
FV on 24 Apr 2020
Closed: MATLAB Answer Bot on 20 Aug 2021
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

Answers (3)

Tommy
Tommy on 24 Apr 2020
How about
i = find(diff(a)==0,1);
  2 Comments
FV
FV on 27 Apr 2020
what if it needs to be repeted three times?
Tommy
Tommy on 28 Apr 2020
Try this:
i=find([diff(a,2)==0;0]&diff(a)==0,1)
On your first example:
>> 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
And your second example:
>> 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
David Hill on 24 Apr 2020
find(diff(a)==0,1);
  3 Comments
FV
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
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.
See inline comments for details.
% 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

This question is closed.

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!