In MATLAB, how to find indexes in vector every time value change from 1 to 0?

  • A+
Category:Languages

I have a vector of 1s and 0s that represent when an intermittent data signal is occurring. E.g.:

    V = [0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1,1,1,0,0,0]; 

How do I find the index value of every change from 1 to 0? So for vector V above, the answer would be:

    idx = [10,18,28]; 

 


Quick and easy:

idx=find(diff(V)<0)+1; 

Compute the derivative, get only the negative values (from 1 to 0 is -1) and find the locations. As the derivatives start from the second location, we need to add 1

However, note that if what you want is accessing data on those locations, it's better to use the logical indices directly, as in:

somevals=my_other_data([false;diff(V)<0]); 

Read more about general variable indexing here

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: