MATLAB: Find the last non-nan in large array

findfunction on dimensionlinear indexMATLABnon-nan

I have very large 4-dimensional arrays with dimensions being time,depth, lat, lon. I want to find the linear index in the depth dimension to the last non-nan data value to I can evaluate the values at the "bottom". I am looking for the output to be 3-D (time, lat, lon) with linear indexes to the last depth with a value (non-nan).
Any idea how to do this efficiently? I have a bunch of very large files to run this on.

Best Answer

One way:
%m: a 4D matrix (time x depth x lat x lon
[~, idx] = max(cumsum(~isnan(m), 2), [], 2)
This relies on the fact that max returns the index of the first max value if several are identical. The first max value of cumsum(~isnan) is the last number before zero or more nan.