How do I remove all the rows with NaN-value of a specific column?

78 views (last 30 days)
Hey, I want to delete all the rows with NaN value of my first column using the 'isnan'-function. The matrix is 570x9.
After I do that I need to delete all columns of the matrix with >25% NaNs, also using the 'isnan'-function.
Thanks in advance for the answers! I'm sure the solution is really basic but I can't get my head around it.

Accepted Answer

dpb
dpb on 21 Nov 2021
X(isnan(X(:,1)),:)=[]; % solution a -- remove those rows w/ NaN in column 1
X=X(~isnan(X(:,1)),:); % solution b -- keep only those rows NOT NaN in column 1
X=X(isfinite(X(:,1)),:); % solution c -- keep only those rows NOT NaN|Inf in column 1
NB: Solution C is a different result than either A or B IFF (if and only if) column one also might contain Inf values besides NaN.
X=X(~isnan(X(:,1)),:);
isGood=sum(isnan(X))<=(size(X,1)/4);
X=X(:,isGood);
  2 Comments
Niklas Weichbold
Niklas Weichbold on 21 Nov 2021
Thank you very much! I'm new to Matlab and haven't figuered out all the different coding options yet
dpb
dpb on 21 Nov 2021
Edited: dpb on 21 Nov 2021
Read the documentation section on logical indexing -- most powerful.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!