Remove rows that contain NaN

조회 수: 5 (최근 30일)
Christopher Wible
Christopher Wible 2019년 6월 19일
댓글: Rik 2019년 6월 19일
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

답변 (1개)

madhan ravi
madhan ravi 2019년 6월 19일
B=A;
B(any(isnan(B),2),:)=[]
  댓글 수: 7
Adam Danz
Adam Danz 2019년 6월 19일
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 2019년 6월 19일
You can also loop backwards
for n=size(A,2):-1:1

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by