How can I remove NaN elements from my data matrix without removing complete columns or rows in MATLAB 7.13 (R2011b)?

3 views (last 30 days)
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.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 5 Sep 2012
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)

More Answers (0)

Categories

Find more on Interpolation in Help Center and File Exchange

Products


Release

R2011b

Community Treasure Hunt

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

Start Hunting!