I have a vector in matlab
a = [1 8 0 7 0 5 9 0 0 0 0 0 0 0 0]
Here I am interested to FIND the first index (beyond which the value are completely zero) where the zeros occur continuously. In this example I expect the answer to be
last_idx = max(find(a~=0)) + 1
however, if your last entry is not a zero you've to be careful...
find pretty much does this for you:
find(a, 1, 'last') + 1
find just returns a list of the positions of non-zero characters, all you have to do is ask
find to only give you the last such element and then the next element (hence the
One approach that works even if your last entry is non-zero or your first entry is zero or all your entries are zero, covers just about everything.
Note that this finds the location of the last group of zeros.