user1185474
user1185474

Reputation: 81

Find where the difference of vector is larger than 1

I can't figure out why this bit of code isn't working:

I have a vector j like this

j=[1;2;4;13;14;19;20]

I am trying to do

for i=2:7
    j1=find(j(i)==(j(i-1)+1)
end

This should give me a j1 of [2,5,7] right? For some reason it's giving me a j1 of either [1] or [0]

Any help would be greatly appreciated, also I am not tied to using find. I just need the indices of j where there is a discontinuity, i.e. for the j I posted it should tell me where it jumps from 1,2 to 4 and from 4 to 13,14 etc.

Upvotes: 1

Views: 658

Answers (1)

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

You can accomplish what you want in a much easier way:

indexes = find( diff(j) > 1)

Regarding your code:

  1. find can be vectorized, no need to use for loop
  2. You keep on reassigning j1. Instead, you can do j1(end+1) = ..

Upvotes: 3

Related Questions