I'm attempting to detrend time-series data in Matlab 2016b. 

My data is in a multidimensional array; each "layer" of the array represents one day of measurements. The size of the area, at 2,500 by 1,700 data points or so, represents the physical boundaries of a city. I have about 100 days of measurements and the location of each data point in each layer's matrix corresponds to its location in the physical world.

Each data point for each day represents a quantifiable biophysical observation (plant greenness). However, since I'm calculating this using satellites, whenever a cloud passes over a pixel (a data point), that point becomes NaN. Approximately half of the days I am working with have NaN over at least some points.

In the image I attached, imagine the middle layer has NaNs in random locations. How could I detrend this so that each point that is detrended uses the maximum available data points? That is, if I were to pull out just the detrended first layer it should have no missing values (since the detrending used either two or three points), the second layer would have missing values where the NaN were, and the 3rd layer would again have no missing values.

I've been able to successfully detrend arrays that have no missing data using detrend3 from the Matlab file exchange (linked below). However, I'm unsure how to detrend an array that has NaN. Detrending with NaN causes the output to be to the lowest common denominator (i.e., if there are 10 pixels to be detrended and one pixel is NaN, then that pixel becomes NaN for all days). I want to detrend with the greatest common factor (i.e., if there are 10 pixels and one pixel is NaN, then the detrending will occur with 9 pixels).

I've tried ignoring NaN, and also changing NaN to -9999 and ignoring that, but haven't got this to work.

Any feedback about which direction to go with this would be greatly appreciated.

https://www.mathworks.com/matlabcentral/fileexchange/61328-detrend3

More Dion Kucera's questions See All
Similar questions and discussions