How can I delete the rows if they have a NaN value?

1 view (last 30 days)
Emre Eryigit
Emre Eryigit on 15 Apr 2021
Commented: Khalid Mahmood on 15 Apr 2021
Hello all,
My problem is kinda cheezy but I still can't solve the problem so here it is;
So my codes I wrote so far are;
load carsmall
and I'd likte to delete the rows which contains NaN in my x value. Long story in short I'd like to delete the rows 11,12,13,14,15 and 18 since they have NaN values.
Any helps are appreciated,

Accepted Answer

Matt J
Matt J on 15 Apr 2021
Matt J
Matt J on 15 Apr 2021
You're welcome, but please Accept-click the answer to indicate that it addressed your question.

Sign in to comment.

More Answers (1)

Khalid Mahmood
Khalid Mahmood on 15 Apr 2021
Edited: Khalid Mahmood on 15 Apr 2021
Let Matrix A has NaN values, we want a matrix B which contains all rows of A except which have NaN values
function testNaNRemoval()
A = [ 1 5 8 ; -3 NaN 14;0 6 NaN ; 1 5 18];
function B = remove_nan_rows(A)
for i=1:size(A,1)
if any(isnan(A(i,:))), continue;end
B(ib,:)=A(i,:); ib=ib+1;
  1 Comment
Khalid Mahmood
Khalid Mahmood on 15 Apr 2021
This is a bit lengthy answer, but keep=~isnan(A); B=A(keep) also works.
Advantage of longer method is when we want mixed behaviour or our tailored processing

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by