Find index of multiple entry in array

Dear,

I need some hep finding the index of multiple entries within an array of integers.

e.g:


A = [1 2 3 4 4 5 6 7 8 8 9]
// expected index
indx = [4 5 9 10]

// The entries of A are to be expected to be consecutive...
// e.g something like 
// A = [1 2 3 4 4 5 6 7 8 8 9 1 1]
// is not expected

// my current approach:

[nrOfEntries dummy] = size(Data);

uniqueEntries = unique( Data);
[nrOfUniqueEntries dummy]= size(uniqueEntries);

I guess I could now iterate through every unique entry by using something like:

for i = 1: nrOfUniqueEntries 
       pos = find (Data = uniqueEntry(i) )
end

but I expect this to be quite slow.

Thank you,
Philipp

Hello, I would propose the following two liner:

A = [1 2 3 4 4 5 6 7 8 8 9];
b = A(2:$)==A(1:$-1);
indx = find([%f, b] | [b, %f])

   4.   5.   9.   10.

Hello,

Thank you indeed.

If you have some extra time:
Can you explain the magic behind the 3rd line?

You select a given index k if A(k)==A(k+1) or A(k-1)==A(k), for relevant values of k, hence if A is of length n you can write this for k=2:n-1 only. For the border cases you have only A(1)==A(2) (first index) and A(n)==A(n-1) (last index). If you want to compute the vector by a single vector operation you can use vector b and its shifted version but in that case you have to add a neutral %f second operand for border cases.

What about?

union(find(diff(A)==0),find(diff(A)==0)+1)

1 Like

Yes, but I think there is more work (in terms of complexity) when computing the union.

S.