Remove rows that contain NaN

4 views (last 30 days)
Christopher Wible
Christopher Wible on 19 Jun 2019
Commented: Rik on 19 Jun 2019
I am currently trying to remove all rows that contain a NaN.
In other words, if you are given this input : A = [ 1 5 8; -3 NaN 14; 0 6 NaN]
The output should be: B = [1 5 8]
This is what I have so far, but I keep getting an error saying the ii index cannot exceed 1.
A = [ 1 5 8
-3 NaN 14
0 6 NaN ];
B = remove_nan_rows(A)
function B = remove_nan_rows(A)
[row,column] = size(A);
for ii = 1:row
for jj = 1:column
if isnan(A(ii,jj)) == 1
A(ii,:) = [];
end
end
end
B = A;
end

Answers (1)

madhan ravi
madhan ravi on 19 Jun 2019
B=A;
B(any(isnan(B),2),:)=[]
  7 Comments
Adam Danz
Adam Danz on 19 Jun 2019
Yeah, good catch. Also, there are some circumstances where you can remove an element from a matrix such as
a = 1:10;
a(2) = [];
so i'll remove that comment to avoid confusion.
Rik
Rik on 19 Jun 2019
You can also loop backwards
for n=size(A,2):-1:1

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!