I can't quite follow what it is that is the key; can you give a short simulated or real set of data and illustrate with it what you're inputs and desired outputs are, please?
I'm positive it can be done; and likely w/o any for loops in Matlab but need more specifics to write actual code.
Meanwhile look for the phrase "logical addressing" in the documentation and perhaps (likely?) nirvana will occur on its own...