Nadine
Nadine

Reputation: 33

finding elements in array which are following a certain value in matlab

assuming I have an array:

[1 5 1 1 3 1 1 1 7]

and I want to find the index of every element which follows a '1', so I would get 2, 5, 9. Does matlab provide anything to do so? Thanks for you help, Nadine

Upvotes: 3

Views: 51

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

Here's another way. Let x be the input vector.

result = find(diff(x==1)<0)+1;

Example:

>> x = [1 5 1 1 3 1 1 1 7];
>> result = find(diff(x==1)<0)+1
result =
     2     5     9

Upvotes: 3

brainkz
brainkz

Reputation: 1345

I suggest the following one-liner:

a = [1 5 1 1 3 1 1 1 7];
idx = find(a(1:end-1) == 1 & a(2:end) ~= 1) + 1

returns:

idx =

     2     5     9

Hope that helps

Upvotes: 6

Related Questions