Removing NaN in 3D array

10 views (last 30 days)
Irene
Irene on 4 Nov 2011
Hi all,
I am working on a 3D array (x,y,t) where I wanted to remove any row containing Nan values. I don't want to reshape my data in a 2D matrix and perform the removal process. Is there a way to do it directly from a 3D data?
thanks, Irene

Accepted Answer

Walter Roberson
Walter Roberson on 4 Nov 2011
If you ask to remove a row out of a 3D matrix, then you are asking to end up with a matrix in which different panes have different number of rows. MATLAB cannot handle such a situation while retaining the 3D structure.
The situation would be different if you were to remove the entire slice:
YourMatrix([2 4],:,:) = []; %valid
This would correspond to
YourMatrix(any(any(isnan(YourMatrix),3),2),:,:) = [];

More Answers (1)

Irene
Irene on 4 Nov 2011
Thanks for your suggestion. I'm afraid this will not work with my data, all the slices have NaN values randomly interspersed. My data is structured as [m,n,t]=[101 101 14], where the first two matrices in the z direction correspond to longitude and latitude and 3 to 14 are values of SST with NaN values. When I reshape it to [m*n,t], I can manage to remove the any row containing NaN. How to get the resulting 2D matrix to the right [m,n,t] structure back, I don't have any idea. Any suggestion will be much appreciated.
  1 Comment
Walter Roberson
Walter Roberson on 4 Nov 2011
Suppose you had 8 rows containing NaN. You start with 101*101 = 10201 rows, and you end with 10201-8 = 10193 rows. Now you want to reshape that in to a 3D matrix. How would you do that, considering that 10193 is a prime number?
The best you will be able to do and retain your 3D structure is to set the entire content of the row containing NaN to be some constant value -- e.g., negative infinity, infinity, NaN, whatever.
Another possibility to consider would be John D'Errico's MATLAB File Exchange contribution http://www.mathworks.com/matlabcentral/fileexchange/4551 "inpaint_nans", which will interpolate values for the NaN locations by examining the surrounding locations.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!