MATLAB: How to remove NaN elements from the data matrix without removing complete columns or rows in MATLAB 7.13 (R2011b)

interpolateinterpolationMATLABnannan'sremovereplace

I am working with a data set containing lots of NaNs (note the attached file). I know that I can easily remove complete rows or columns containing NaN elements:
dat=dlmread('scatteredNans.dat');
dat(isnan(sum(dat,2)),:)=[];
However the NaNs are scattered, so almost every row and column is containing at least one NaN element. Removing those rows and columns will leave no data to work with. Replacing the NaN elements with a constant value (like zero) is also not possible as it will add to much distortion.

Best Answer

In order to remove NaNs from a dataset containing many scattered NaN elements you can use the TriScatteredInterp class to interpolate the missing data. This step requires some preprocessing as the NaN elements will be propagated in the interpolation phase, producing even more NaN elements:
%%find values that are not NaN
[row,col]=find(~isnan(dat));
%%convert to linear indices
indA=sub2ind(size(dat),row,col);
%%create interpolant
F=TriScatteredInterp(col,row,dat(indA));
%%prepare meshgrid (to fill the original matrix)
[xn,yn]=meshgrid(1:size(dat,2),1:size(dat,1));
%%interpolate missing values
zn=F(xn,yn);
%%compare results
subplot(211)
stem3(dat)
subplot(212)
stem3(zn)