MATLAB: How to find the highest value in an array that is smaller than the value at i+1

datafilterfor loopindexmatchmaxtime series

I have 1D arrays, one is labelled start_event, and one labelled end_event. The start_event array marks the index at which an event in another array starts. This has been subjected to other filters, so that the end_event array no longer matches. What I need to do would be to get the value at index i in end_event where it is the highest possible value that is still smaller than start_event(i+1), i.e. the events should not overlap, but should run as long as possible. An example:
start_event=
2
212
260
284
472
560
end_event=
5
6
10
84
175
183
258
266
271
324
493
523
576
What I would then like as an output for filtering end_event is
end_event=
183
258
271
324
523
576
That way, each event is closed in itself and has the maximal span available in the unfiltered end_event data.
I have tried it like this, but obviously something is wrong because my output is a long list of zeros with 1s thrown in:
for i=1:length(start_event)-1
for k=1:length(end_event)
end_event_f(k)=max(end_event(end_event(k)>start_event(i) && end_event(k) < start_event(i+1)));
end
end
I'd appreciate any help!

Best Answer

end_event_f = nan(size(start_event)); %predeclare for speed
for evidx = 1 : numel(start_event) - 1
end_event_f(evidx) = end_event(find(end_event < start_event(evidx+1), 1, 'last'));
end
end_event_f(end) = end_event(end)
Related Question