How do I find the start position (index) of a cluster of non-zero values in a vector?
1 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Star Strider
2015-2-8
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’.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!