How do I find the start position (index) of a cluster of non-zero values in a vector?

1 Ansicht (letzte 30 Tage)
Lets say I have a vector that is populated with zeros apart from in a few clusters where its populated by ones.
I.e. x= [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 ...]
Does anyone have any ideas/code on how to easily return the indices of the start of each cluster? I.e. so I'd get
start_positions=[11 29 42 ...]
It has to be the start of the clusters, I've already got a code that would be able to find the end of them.
Thanks a bunch!

Akzeptierte Antwort

Star Strider
Star Strider am 8 Feb. 2015
You could combine these into one statement if you want to. I kept them separate so you can explore ‘dx’ to see how the code works:
x= [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1];
dx = diff([0,x]);
x1idx = find(dx > 0)
produces:
x1idx =
11 29 42
The leading ‘0’ in the diff call vector makes the indices come out the same between ‘x’ and ‘dx’.

Weitere Antworten (0)

Kategorien

Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by