I am working in MATLAB with a signal data that consist of consecutive dips as shown below. I am trying to write a code which sorts the contents of each dip into a separate group. How should the general structure of such a code look like?

The following is my data. I am only interested in the portion of the signal that lies below a certain threshold d (the red line):

And here is the desired grouping:

Here is an unsuccessful attempt:

```
k=0; % Group number
for i = 1 : length(signal)
if signal(i) < d
k=k+1;
while signal(i) < d
NewSignal(i, k) = signal(i);
i = i + 1;
end
end
end
```

The code above generated 310 groups instead of the desired 12 groups.

Any explanation would be greatly appreciated.

Taking Benl generated data you can do the following:

This idea is taken from here

Comments: First of all I choose an arbitrary threshold, it is up to you to find the "best" one in your data. Additionally I didn't group the data explicitly but rather this approach gives you the start and end of each epoch with a dip (you might call it group). So you could say that each index is the grouping index. Finally I did not debug this approach for corner cases, when dips fall on starts and ends...