MATLAB: Identify first and last indicies of numbers in an array containing NaN’s

findindex

I have an array containing numbers and NaN's. The numbers and NaN's are interspersed with each other:
M = [NaN, 1.3, 4, 5.2, 3, NaN, NaN, NaN, 4.6, 2, 6.2, 3, 2, NaN, 7, 3.2, 5, NaN, NaN, NaN, 12.1 ,6.8];
I want to extract the first and last indicie of each section containing real numbers. In this example it would be
startIndex = [2, 9, 15, 21];
endIndex = [5, 13, 17, 22];
I know I can find the index of each non NaN value by:
index = find(~isnan(M));
index = [2, 3, 4, 5, 9, 10, 11, 12, 13, 15, 16, 17, 21, 22];
The first derivative would help me identify the break points in the index array:
idx = find(diff(index));
idx = [1, 1, 1, 4, 1, 1, 1, 1, 2, 1, 1, 4, 1];
I'm now stuck on how to use that to get the data that I want.
Thanks in advance!

Best Answer

Your original idea of using diff is exactly the simple and efficient solution that experienced MATLAB users would use:
>> M = [NaN,1.3,4,5.2,3,NaN,NaN,NaN,4.6,2,6.2,3,2,NaN,7,3.2,5,NaN,NaN,NaN,12.1,6.8];
>> D = diff([true;isnan(M(:));true]);
>> B = find(D<0)
B =
2
9
15
21
>> E = find(D>0)-1
E =
5
13
17
22