Search code examples
matlabvectorfindposition

Find a number before another specific number on a vector


so I'm trying to know when an event happened before another event in matlab; by event I mean number. For example, I have a vector, let's say:

x = [0.3 0.3 0.1 0.2 0.5 0.1 0.3 0.1 0.5 0.1 0.4 0.5]

and I want to know in which position is the 0.1 that happened before a 0.5. I tried with find(x,0.5,'last') but that doesn't help much since I want to then find the 0.1. I thought about maybe creatig another vector that ended at the 0.5 and then search for the last 0.1 but that would just be sort of inefficient since my vectors contain ~300 events.


Solution

  • You can try this if you want .5 immediately to appear after .1

    idx = [x(1:end-1)==0.1 & x(2:end)== 0.5 false]
    

    that generates a logical index, for numeric index you can use

    find(idx)
    

    Update: to find all .1 s that have .5 after them without having any .1 appear between those .1 and .5

    f= find(x==.1 | x==.5)
    f(x(f(1:end-1)) < x(f(2:end)))