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

2 vues (au cours des 30 derniers jours)
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!

Réponse acceptée

Star Strider
Star Strider le 8 Fév 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’.

Plus de réponses (0)

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by