title: Ignore NaN when detrending 3-d array
body: <p>I'm using Matlab 2016a; I'm attempting to detrend a 3-dimensional array along the third dimension, but where there are missing values. It is critical that the values stay in the same positions in the array since the position relates to a geographic location. <a href="https://i.stack.imgur.com/SSWbl.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SSWbl.gif" alt="3-d array"></a></p>
  
  <p>In this image, imagine that Page 2 has NaN at random locations but that Page 1 and Page 3 have complete data. Detrending along the 3rd dimension, some vectors will have three data points and some will have two. I need to be able to detrend along the third dimension using all available values. If I were to look at the values for the detrended Page 1 or Page 3, there should be no missing values (since there are always either 2 or 3 data points to use), but Page 2 would have NaN placeholders in the location where the NaN was located.</p>
  
  <p>My question is: how can I detrend along the third dimension while ignoring NaN?</p>
  
  <p>I've attempted using detrend3 (found on the Matlab file exchange: <a href="https://www.mathworks.com/matlabcentral/fileexchange/61328-detrend3?focused=7203929&amp;tab=function" rel="nofollow noreferrer">https://www.mathworks.com/matlabcentral/fileexchange/61328-detrend3?focused=7203929&amp;tab=function</a>), which works perfectly when detrending 3-d arrays with no missing values.</p>
  
  <p>Detrending with NaN present produces an error. I've tried ignoring NaN and also setting NaN to -9999 and then ignoring that number, but have been unable to get these efforts to work.</p>
  
  <p>Any guidance about what direction to go would be greatly appreciated.</p>