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

2 views (last 30 days)
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!

Accepted Answer

Star Strider
Star Strider on 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’.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!